Created
November 3, 2017 23:05
-
-
Save melastmohican/90f883f1ebfef05f571b64c55e072799 to your computer and use it in GitHub Desktop.
Get Nth element from the end in a linked list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| Get Nth element from the end in a linked list of integers | |
| Number of elements in the list will always be greater than N. | |
| Node is defined as | |
| struct Node | |
| { | |
| int data; | |
| struct Node *next; | |
| } | |
| */ | |
| int GetNode(Node *head,int k) | |
| { | |
| if(head == NULL) return -1; | |
| Node *p1 = head; | |
| Node *p2 = head; | |
| for (int i = 0 ; i < k ; i++) { | |
| if(p2 == NULL) return -1; | |
| p2 = p2->next; | |
| } | |
| if( p2 == NULL) return -1; | |
| while(p2->next != NULL) { | |
| p1 = p1->next; | |
| p2 = p2->next; | |
| } | |
| return p1->data; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment