Skip to content

Instantly share code, notes, and snippets.

@jason51122
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jason51122/2873201611ad2675b5a3 to your computer and use it in GitHub Desktop.
Save jason51122/2873201611ad2675b5a3 to your computer and use it in GitHub Desktop.
2.2 Implement an algorithm to find the kth to last element of a singly linked list.
ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
next = null;
}
}
ListNode linkedListKthToLast(ListNode head, int k) {
if (head == null || k < 1) {
return null;
}
ListNode slow = head;
ListNode fast = head;
for (int i = 2; i <= k; i++) {
fast = fast.next;
if (fast == null) {
return null;
}
}
while (fast.next != null) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment