Created
April 27, 2012 09:42
-
-
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
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
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