我正在练习基本的数据结构,但是在递归方面遇到了一些困难。 我明白如何通过迭代来实现,但是我的所有尝试通过递归返回链表中倒数第n个节点都会返回空值。这是我目前的代码:
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;
}