Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created May 9, 2016 18:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/d4da2ec82876d93bcd1920927054702d to your computer and use it in GitHub Desktop.
Save jianminchen/d4da2ec82876d93bcd1920927054702d to your computer and use it in GitHub Desktop.
HackerRank - Linked List - get Node Value
/*
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