Skip to content

Instantly share code, notes, and snippets.

@melastmohican
Created November 3, 2017 23:05
Show Gist options
  • Select an option

  • Save melastmohican/90f883f1ebfef05f571b64c55e072799 to your computer and use it in GitHub Desktop.

Select an option

Save melastmohican/90f883f1ebfef05f571b64c55e072799 to your computer and use it in GitHub Desktop.
Get Nth element from the end in a linked list
/*
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