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

You’re given the pointer to the head node of a linked list and a specific positi

ID: 3838275 • Letter: Y

Question

You’re given the pointer to the head node of a linked list and a specific position. Counting backwards from the tail node of the linked list, get the value of the node at the given position. A position of 0 corresponds to the tail, 1 corresponds to the node before the tail and so on.

int GetNode(Node *head,int positionFromTail) {
Node* p = head;
int count = 0;
while (p != NULL) {
p = p->next;
count++; //create count
}
int nodePositionFromHead = count - positionFromTail; // find position from beginning of linked list.
p = head;
for (int i = 0; i < theNodePosition; i++) {
p = p->next;
}
return p->data;
}

I do not understand why this is wrong. The logic looks correct to me.

Explanation / Answer

//Please try getting node position from head using below statement:-                                                     int nodePositionFromHead = count -positionFromTail - 1;                                                 

since tail node corresponds to position of 0,if position from tail is given 1 and total nodes are 5, that means you need to print 4th node from the beginning.That means your for loop should run 3 times to point to 4th node. In your current code, this will not happen , code will run 4 times and will come out of it pointing to 5th node from beginning. Hence please correct the code as given above and try.You can also start for loop with i=1 and this would also solve the problem.