2.2 Kth element linked list

Problem

Implement an algorithm to find the kth to last element of a singly linked list.

Solution

 1 public static ListNode findElement(ListNode head, int k) {
 2     if(k <= 0)    return null;
 3     
 4     ListNode fast = head;
 5     ListNode slow = head;
 6     
 7     for(int i=0; i<k-1; i++) {
 8         if(fast == null) return null; //edge case
 9         fast = fast.next;
10     }
11     
12     //fast = null
13     if(fast == null) {
14         return null;
15     }
16     
17     while(fast.next != null) {
18         fast = fast.next;
19         slow = slow.next;
20     }
21     
22     return slow;
23 }

 

posted on 2014-11-22 10:10  SuperBo  阅读(232)  评论(0编辑  收藏  举报