Implement an algorithm to find the kth to last element of a singly linked list.
LinkedListNode nthToLast(LinkedListNode head, int k) {
if(k <= 0) return null;
LinkedListNode prev = head;
LinkedListNode cur = head;
while(cur && k > 1){
cur = cur.next;
k--;
}
if(!cur) return null;
while(cur.next){
cur = cur.next;
prev = prev.next;
}
return prev;
}
No comments:
Post a Comment