Skip to content

Instantly share code, notes, and snippets.

@zac-xin
Created April 27, 2012 09:42
Show Gist options
  • Save zac-xin/2507861 to your computer and use it in GitHub Desktop.
Save zac-xin/2507861 to your computer and use it in GitHub Desktop.
2.2 Implement an algorithm to !nd the nth to last element of a singly linked list
public AnyType findLastNth(int k){
if(head == null || k <= 0)
return null;
if(size() < k)
return null;
Node<AnyType> tmp = head;
for(int i = 0; i < k; i++)
tmp = tmp.next;
Node<AnyType> p = head;
while(tmp != null){
tmp = tmp.next;
p = p.next;
}
return p.data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment