input 1---->2--->3---6>----7--->null
find 3rd node in linked list
public ListNode NthNodeFromEnd(ListNode head, int NthNode) {
ListNode ptemp = head;
ListNode pNthNode = null;
for (int i = 1; i < NthNode; i++) {
ptemp = ptemp.getNext();
}
while (ptemp != null) {
if (pNthNode == null) {
pNthNode = head;
} else {
pNthNode = pNthNode.getNext();
}
ptemp = ptemp.getNext();
}
return pNthNode;
}
No comments:
Post a Comment