Please break down objectives and explain what needs to be done before implementi
ID: 3825737 • Letter: P
Question
Please break down objectives and explain what needs to be done before implementing the code?
Thank you.
Consider the following struct Node. Write a function insertIth(headPtr, pos, value) which takes a pointer to a linked list pointed to by headPtr and adds a new Node with value as its data in the posth position of the resultant list. If pos is 0, then the new Node will be first. If pos is greater than the length of the current list, the new Node will be last. struct Node { int data; Node * next; }; Example Usage // If list[1->[3->[5-> nullptr; insertIth(list,0,7); // results in list[7->[1->[3->[5->nullptr; // If list[1->[3->[5-> nullptr; insertIth(list,2,7); // results in list[1->[3->[7->[5-> nullptr;
Explanation / Answer
Hi, Please find my implementation of required method.
Node* insertIth(Node *head, int data, int position)
{
Node *newNode = new Node;
newNode->data = data;
if (head == NULL) {
return newNode;
}
if (position == 0) {
newNode->next = head;
return newNode;
}
Node *currentNode = head;
while (position - 1 > 0) {
currentNode = currentNode->next;
position--;
}
newNode->next = currentNode->next;
currentNode->next = newNode;
return head;
}