您的位置:首页 > 其它

LinkLists 链表中返回倒数第n个元素 @CareerCup

2014-02-28 11:44 351 查看
原文:

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

译文:

实现一个算法从一个单链表中返回倒数第n个元素。

思路:

1 递归(头递归),在递归过程中,递归到倒数第k个时直接打印出来。如果需要保存那个值,则可以建一个wrapper类来存放,或者用全局变量

2 Iterative 双指针,先让快指针超前慢指针k个距离,然后让快慢指针同步往前走,直到快指针碰到链表尾。

package LinkLists;

import CtCILibrary.AssortedMethods;
import CtCILibrary.LinkedListNode;

public class S2_2 {

// 递归1,直接打出来
public static int nthToLast(LinkedListNode head, int k) {
if(head == null) {
return 0;
}

int i = nthToLast(head.next, k) + 1; // 当前倒数等于后一个倒数加上1
if(i == k) {
System.out.println(head.data);
}

return i;
}

// 递归2,用一个wrapper类,相当于与一个全局变量
public static LinkedListNode nthToLast2(LinkedListNode head, int k, IntWrapper wrapper) {
if(head == null) {
return null;
}
LinkedListNode node = nthToLast2(head.next, k, wrapper);
wrapper.value++;
if(wrapper.value == k) {
return head;
}
return node;
}

static class IntWrapper {
public int value = 0;
}

// Iterative的方法,双指针,让两个指针间相差k个距离,当快指针走到头时,返回慢指针的位置
public static LinkedListNode nthToLast3(LinkedListNode head, int k) {
if(k < 0) {
return null;
}

LinkedListNode cur=head, probe=head;
for(int i=0; i<k-1; i++) {
if(probe == null) { // k太大
return null;
}
probe = probe.next;
}

if(probe == null) {
return null;
}

// 两个指针一起往前走,直到probe指针走到头
while(probe.next != null) {
cur = cur.next;
probe = probe.next;
}
return cur;
}

public static void main(String[] args) {
LinkedListNode head = AssortedMethods.randomLinkedList(10, 0, 10);
System.out.println(head.printForward());
int nth = 3;
IntWrapper wr = new IntWrapper();
nthToLast(head, nth);
LinkedListNode n = nthToLast2(head, nth, wr);
if (n != null) {
System.out.println(nth + "th to last node is " + n.data);
} else {
System.out.println("Null. n is out of bounds.");
}
LinkedListNode n2 = nthToLast3(head, nth);
System.out.println(n2.data);
}

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