您的位置:首页 > 其它

2.2---找链表倒数第K个结点

2015-12-17 12:31 267 查看
答案,注意,一种是递归,另一种是迭代,那么巧妙利用双指针:

迭代:

public static LinkedListNode nthToLast(LinkedListNode head, int n) {
LinkedListNode p1 = head;
LinkedListNode p2 = head;

if (n <= 0) return null;

// Move p2 n nodes into the list.  Keep n1 in the same position.
for (int i = 0; i < n - 1; i++) {
if (p2 == null) {
return null; // Error: list is too small.
}
p2 = p2.next;
}
if (p2 == null) { // Another error check.
return null;
}

// Move them at the same pace.  When p2 hits the end,
// p1 will be at the right element.
while (p2.next != null) {
p1 = p1.next;
p2 = p2.next;
}
return p1;
}


View Code
递归:

public static int nthToLastR1(LinkedListNode head, int n) {
if (n == 0 || head == null) {
return 0;
}
int k = nthToLastR1(head.next, n) + 1;
if (k == n) {
System.out.println(n + "th to last node is " + head.data);
}
return k;
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: