Consider the following struct Node. Write a function insertIth(headPtr, pos, val
ID: 3825204 • Letter: C
Question
Consider the following struct Node. Write a function insertIth(headPtr, pos, value) whihc takes a pointer to a linked list pointed tp by the headPtr and adds a new Node with value as its data in the pos(th) position of the restaurant list.
If pos is 0 , then the new Node will be first. If pos is greater then the length of the current list, the new Node will be last.
struct Node
{
int data;
Node * next;
};
I'm super confused as to what my my professor is asking. I dont really understand the question. Anything help would be great.
So far I have the function set up as void insertIth(Node*headPtr, int pos, int value) is this correct?
Explanation / Answer
Please find my implementation.
Please let me know in case of any issue.
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;
}