加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 16:18:24 所属栏目: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 Lis
调用方法后,
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个元素.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读