简体   繁体   中英

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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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