Skip to content

Instantly share code, notes, and snippets.

@gaoyike
Created June 23, 2014 08:41
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 gaoyike/9eef63abd6756e1f13f8 to your computer and use it in GitHub Desktop.
Save gaoyike/9eef63abd6756e1f13f8 to your computer and use it in GitHub Desktop.
2.2
/**
* 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