你需要结束,然后计算你的方式,确保每次传回回传节点.我喜欢一个回归点
public static int i = 0;
public static Link.Node findnthToLastRecursion(Link.Node node,int pos) {
Link.Node result = node;
if(node != null) {
result = findnthToLastRecursion(node.next,pos);
if(i++ == pos){
result = node;
}
}
return result;
}
工作示例从第9个和最后一个节点输出7为2:
public class NodeTest {
private static class Node {
E item;
Node next;
Node prev;
Node(Node prev,E element,Node next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
/**
* @param args
*/
public static void main(String[] args) {
Node first = null;
Node prev = null;
for (int i = 0; i < 10; i++) {
Node current = new Node(prev,Integer.toString(i),null);
if(i==0){
first = current;
}
if(prev != null){
prev.next = current;
}
prev = current;
}
System.out.println( findnthToLastRecursion(first,2).item);
}
public static int i = 0;
public static Node findnthToLastRecursion(Node node,int pos) {
Node result = node;
if (node != null) {
result = findnthToLastRecursion(node.next,pos);
if (i++ == pos) {
result = node;
}
}
return result;
}
}