CC150 : Kth to last Element of Linked List

递归版,因为既要传一个node也要传数字回来,所以只能写个wrapper。

class Solution {
class IntWrapper {
public int value = 0;
}

public ListNode kthLast(ListNode head, int k, IntWrapper i) {
if(head == null) return null;
ListNode node = kthLast(head.next, k, i);
i.value = i.value + 1;
if(k == i.value) {
node = head;
}
return node;
}
}


非递归版: 

class Solution {
public ListNode kthLast(ListNode head, int k) {
ListNode l1 = head, l2 = head;
for(int i = 0; i < k; i++) {
if(l2 == null) return null;
l2 = l2.next;
}
while(l2 != null) {
l1 = l1.next;
l2 = l2.next;
}
return l1;
}
}


posted @ 2015-02-19 10:01  江南第一少  阅读(143)  评论(0编辑  收藏  举报