【发布时间】:2013-12-10 22:14:01
【问题描述】:
我正在练习基本的数据结构,但在递归方面遇到了一些困难。我知道如何通过迭代来做到这一点,但是我所有通过递归从链表的最后一个节点返回第 n 个节点的尝试都导致 null。到目前为止,这是我的代码:
public static int i = 0;
public static Link.Node findnthToLastRecursion(Link.Node node, int pos) {
if(node == null) return null;
else{
findnthToLastRecursion(node.next(), pos);
if(++i == pos) return node;
return null;
}
谁能帮我理解我哪里出错了?
这是我的迭代解决方案,效果很好,但我真的很想知道如何将其转换为递归:
public static Link.Node findnthToLast(Link.Node head, int n) {
if (n < 1 || head == null) {
return null;
}
Link.Node pntr1 = head, pntr2 = head;
for (int i = 0; i < n - 1; i++) {
if (pntr2 == null) {
return null;
} else {
pntr2 = pntr2.next();
}
}
while (pntr2.next() != null) {
pntr1 = pntr1.next();
pntr2 = pntr2.next();
}
return pntr1;
}
【问题讨论】:
-
第一次调用时
node的值是多少?您是向前还是向后工作?我原以为您需要从头开始并致电previous(),或者如果您不知道结尾是什么,请从头开始,一直工作到最后,然后退出n次。这段代码没有做那样的事情...... -
找不到最后一个节点的位置(或大小),怎么知道第n个最后一个节点?这(如果编写正确)将找到第 n - 1 个节点(不是第 n 个最后一个节点)
-
快速提问:你知道你的链表的长度是多少
-
初始值为head,没有previous()函数可以调用。从头开始,一直工作到结束,然后通过迭代退出 n 次对我来说是有意义的,但我似乎无法理解如何递归地做到这一点。
-
@user3029486 就个人而言,我认为没有一种递归方式的好方法。是的,有办法,但没有一个是好的
标签: java recursion linked-list