Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the "Nth node from the end" of a linked list

Tags:

This seems to be returning the correct answer, but I'm not sure if this is really the best way to go about things. It seems like I'm visiting the first n nodes too many times. Any suggestions? Note that I have to do this with a singly linked list.

Node *findNodeFromLast( Node *head, int n ) {     Node *currentNode;     Node *behindCurrent;     currentNode = head;     for( int i = 0; i < n; i++ ) {         if( currentNode->next ) {             currentNode = currentNode->next;         } else {             return NULL;         }     }      behindCurrent = head;     while( currentNode->next ) {         currentNode = currentNode->next;         behindCurrent = behindCurrent->next;     }      return behindCurrent; } 
like image 820
Stephano Avatar asked Feb 26 '10 22:02

Stephano


People also ask

What will be the time complexity of finding Nth node from the end of a singly?

Time Complexity: O(N), where N is the length of given linked list. In this program, we will use a user defined function "getNthLastNode" which takes head node pointer of a linked list and N as input parameters and return a pointer to Nth last node of linked list. Given a Inserts a node in front of a singly linked list.


1 Answers

Another way to do it without visiting nodes twice is as follows:

Create an empty array of size n, a pointer into this array starting at index 0, and start iterating from the beginning of the linked list. Every time you visit a node store it in the current index of the array and advance the array pointer. When you fill the array, wrap around and overwrite the elements you stored before. When you reach the end of the list, the pointer will be pointing at the element n from the end of the list.

But this also is just an O(n) algorithm. What you are currently doing is fine. I see no compelling reason to change it.

like image 140
Mark Byers Avatar answered Nov 04 '22 22:11

Mark Byers