微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 在递归中查询此变量的用法

调用方法后,
node.nth(5)

在下面的代码中,

public class List_Node {
    int item;
    List_Node next;
    public List_Node() {
        this.item = 0;
        this.next = null;
    }
    public List_Node(int item,List_Node next) {
        this.item = item;
        this.next = next;
    }
    public List_Node(int item) {
        this(item,null);
    }
    public void insertAfter(int item) {
        this.next = new List_Node(item,this.next);
    }
    public List_Node nth(int position) {
        if (position == 1) {
            return this;
        } else if((position < 1) || (this.next == null)) {
        /* error checking */
            return null;
        } else {
            return this.next.nth(position - 1);
        }
    }
    public static void main(String[] args){
        List_Node node = new List_Node(0);
        List_Node temp = node;
        for (int item = 1; item < 5; item++) {
            temp.insertAfter(item);
            temp = temp.next;
        }
        System.out.println(node.nth(5).item);
    }
}

下面是我在4次递归调用后可以想象的nth()方法的堆栈框架.

我的问题:

根据上图,假设在激活记录S5中的值为pos的情况为1,我想了解,当java执行时返回这一点会发生什么?
在S4中,java将值分配给这个值吗?因为在nth()方法的else {}块中没有赋值语句(如此).

注意:请忽略Java编码风格,就像新的学习者一样.

解决方法

每次调用this.next.nth()时,都会在完全不同的对象上调用nth()方法.你的这个将引用这个新对象(在之前的堆栈中是下一个).它不是纯粹的递归.就像在不同的对象上调用不同的方法一样.

所以当position = 1时,这将参考S5.

UPDATE
让我们说你的List_Nodes是这样链接
10→20→; 30-> 40-→50

每当你从main调用node.nth(5)

Stack 1: position 5,this points to 10 (you are calling this.next.nth(4); means 20.nth())
    Stack 2: position 4,this points to 20 (calling this.next.nth(3); = 30.nth())
        Stack 3: position 3,this points to 30 (calling this.next.nth(2) = 40.nth())
            Stack 4: position 2,this points to 40 (calling this.next.nth(1) = 50.nth())
                Stack 5: position 1,this points to 50 (returning this; this here is 50)
                returns 50
            returns 50 (not going back into if,so return value remains same)
        returns 50
    returns 50
returns 50

在聊天聊天的同时,也在图片中描述了这一点.在这里添加,以使未来的读者受益.

一个UPDATE

No assignment variable in else as such

你可以这样写

List_Node temp = this.next.nth(position-1);
return temp;

一般来说,我们需要分离List和Node类,你的List应该有一个头,你的Node将有item和next指针.就像java中的LinkedList一样.那么nth()方法将在List类中,它只是遍历它,直到到达第n个元素.

原文地址:https://www.jb51.cc/java/125892.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐