-
-
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.
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
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