Created
May 9, 2016 18:46
-
-
Save jianminchen/d4da2ec82876d93bcd1920927054702d to your computer and use it in GitHub Desktop.
HackerRank - Linked List - get Node Value
This file contains 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 positionFromTail) | |
{ | |
if(head == NULL || positionFromTail < 0) | |
return NULL; | |
Node * runner = head; | |
Node * prevLast = NULL; | |
int count = 0; | |
while(runner!=NULL) | |
{ | |
if(count == positionFromTail) | |
prevLast = head; | |
else if(count> positionFromTail) | |
prevLast = prevLast->next; | |
runner = runner->next; | |
count ++; | |
} | |
return prevLast->data; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment