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; }
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With