什么" node = node.next"意思?

时间:2016-02-25 18:36:55

标签: java

在单链表中,指定

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

在代码中,它说

ListNode result = new ListNode(0);
s = 7;
result.next = new ListNode(s);
result = result.next;
System.out.println(result.next);

我不知道为什么我没有得到我想要的东西。首先,当我返回result.next时,我认为指针应该移到LinkedList的开头并给我7但实际上它什么都没打印。第二,result = result.next的含义是什么?这是否意味着指针移动到下一个节点?第三,我只想将7放在ListNode中,但是如果我不放句ListNode result = new ListNode(0);,程序将在编译时失败。

2 个答案:

答案 0 :(得分:2)

你想要做的事情并不那么明显。

也许这些评论会有所帮助:

// create a new ListNode object with content 0, and put a reference to it
// in 'result'. At this stage it's 'next' field is null.
ListNode result = new ListNode(0);

s = 7;

// create a new ListNode object with content 7 and a null 'next' field,
// and make the first ListNode object's 'next' field refer to it.
result.next = new ListNode(s);

// now lose the reference to the first object, and instead make 'result'
// point to the second object. At this stage its 'next' field is still null.
result = result.next;

// now print the contents of the 'next' field of the second object, which
// will be null.
System.out.println(result.next);

重新提出你的第一个问题,或许你打算在最后打印result.val,这确实是7.打印一个对象引用不会在没有进一步的情况下给你那个对象的val字段工作(例如覆盖toString()

根据上面的评论,回答你的第二个问题,是的,你实际上是在链表上移了一步,所以'结果'现在指向您分配的第二个ListNode(内容7)。

我不明白你的第三个问题。您已分配了两个ListNode。如果您只想要一个,那么请执行:

result = new ListNode(7);

答案 1 :(得分:2)

您收到此错误的原因是当您调用System.out.println(result.next)时result.next为null。让我们逐行遍历代码:

ListNode result = new ListNode(0);
//--this creates a node result : [0] -> null
//                                ^result pointing to this node
s = 7;
result.next = new ListNode(s);
//--this sets result.next to a new node with value 7 : [0] ->  [7] -> null
//                                                      ^result ^result.next
result = result.next;
//--this moves result over to '7' node : [0] -> [7] -> null
//                                               ^result ^result.next
System.out.println(result.next);
//--from this: [0] -> [7] -> null
//                     ^result ^result.next
//we can see that at this point in time, result.next = null

要回答有关“node = node.next是什么意思”的问题,这意味着引用将“滑动”到下一个节点的任何节点。从LinkedList可视化:

[0] - > [7] - >空

- ^ node ^ node.next

致电后:

node = node.next;

[0] - > [7] - >空

-------- ^ node ^ node.next

(编辑:回答评论中的问题:)

迭代LinkedList通常按如下方式进行:

ListNode result = new ListNode(0);
result.next = new ListNode(7);
while(result != null){
    System.out.println(result.val);
    result = result.next;'
}
相关问题