Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Implement the insertAtPosition function of the LinkedList class . bool LinkedLis

ID: 3800319 • Letter: I

Question

Implement the insertAtPosition function of the LinkedList class .

bool LinkedList::insertAtPosition(int position, int d)

The job of this function is to insert a new node with given data d in the given position.

If position is less than 1 or greater than length + 1 then the function should leave the list unchanged and return false .

If given a legal position, the function will insert a new node with data d at that position and return true . For example, if the list is initially { 1, 2, 3 } and we call insertAtPosition(2, 20) then the list will be changed to { 1, 20, 2, 3 }.

Explanation / Answer

bool LinkedList::insertAtPosition(int position, int d)
{
int counter = 0; //counter to get the boundary of the LinkedList
struct node *temp, *s, *ptr;
//a new node is created. (Assumed that the memory space is available and new node is created without any error)
temp = new(struct node);
temp->info = value;
temp->next = NULL; //the new node is initialized with the given value
int i;
s = start;//Given that start is NULL when there is no element in the LinkedList
while (s != NULL)
{
s = s->next;
counter++;
}
if (position == 1) //checking if the position is the 1st element
{
if (start == NULL)
{
start = temp;
start->next = NULL;
}
else
{
ptr = start;
start = temp;
start->next = ptr;
}
return true;
}
else if (position > 1 && position <= counter) // if the position is not the first element and it does not go out of range
{
s = start;
for (i = 1; i < position; i++)
{
ptr = s;
s = s->next;
}
ptr->next = temp;
temp->next = s;
return true;
}
else
{
return false;//if out of range
}
}

I HOPE THIS HELPS.

THANKS FOR USING CHEGG