-
-
Save gaoyike/9eef63abd6756e1f13f8 to your computer and use it in GitHub Desktop.
2.2
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
/** | |
* Created by Readman on 6/23/14. | |
*/ | |
public class lastKth { | |
/* | |
time n | |
space 1 | |
* */ | |
public static ListNode kth(int k, ListNode head) { | |
ListNode slow = head; | |
ListNode fast = head; | |
while (k > 0) { | |
fast = fast.next; | |
k--; | |
} | |
while (fast != null) { | |
fast = fast.next; | |
slow = slow.next; | |
} | |
return slow; | |
} | |
public static void main(String[] args) { | |
ListNode first = new ListNode(1); | |
first.next = new ListNode(2); | |
first.next.next = new ListNode(3); | |
first.next.next.next = new ListNode(4); | |
first.next.next.next.next = new ListNode(5); | |
first.next.next.next.next.next = new ListNode(6); | |
System.out.println(kth(2,first).val); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment