简体   繁体   English

为什么不能修改在所述循环内的循环外声明的LinkedList?

[英]Why can't I modify a LinkedList declared outside a loop inside said loop?

I'm trying to create a LinkedList that's added to by going through a loop. 我正在尝试创建一个通过循环添加到其中的LinkedList。

public class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

public class Something {
    public void method() {

        ListNode node = null;
        ListNode out = node;
        for (int i = 0; i < 10; i++) {
            node = new ListNode(i);
            node = node.next;
        }

    return out;
    }
}

The way this works in my head is like this: 这在我脑海中的运作方式是这样的:

node->null;

node->null;
       ^
       |
      out

out->0->null
          ^
          |
         node
...
out->0->1->2->3->4->5->6->7->8->9->null
                                     ^
                                     |
                                   node

However, out returns null, as if the loop never ran at all. 但是, out返回null,就好像循环根本不会运行。 How do I get the behavior that I described? 如何获得我描述的行为?

This should probably work as intended. 这可能应该按预期工作。 You first have to assign an initial node where you assign the next node. 首先,您必须分配一个初始节点,然后再分配下一个节点。 And on the newly created next node, you create even further the next node. 在新创建的下一个节点上,您甚至可以进一步创建下一个节点。

public static void main(String[] args) {
    ListNode k = Something.method();

    while(k.next != null){
        System.out.println(k.val);
        k = k.next;
    }

}

private static class ListNode {
    int val;
    ListNode next = null;
    ListNode(int x) { val = x; }
}

public static class Something {
    public static ListNode method() {

        ListNode node = new ListNode(0);
        ListNode out = node;

        for (int i = 1; i < 10; i++) {
            node.next = new ListNode(i);
            node = node.next;
        }

        return out;
    }
}

And afterward, you return your initial node, which contains your "first" node a next node. 然后,返回初始节点,该节点包含“第一个”节点和下一个节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM