java“node=node.next”是什么意思?
在单链表中,指定
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);
放在句子中,程序将无法编译
# 1 楼答案
你想做什么其实并不那么明显
或许这些评论将有助于:
这是你的第一个问题,也许你想在最后打印
result.val
,实际上是7。如果不做进一步的工作(例如重写toString()
),打印对象引用不会为您提供该对象的val
字段如果是您的第二个问题,根据上面的评论,是的,您实际上是沿着链接列表移动了一步,因此“result”现在指向您分配的第二个
ListNode
(contents7
)我不明白你的第三个问题。您已分配了两个
ListNode
。如果您只需要一个,请执行以下操作:# 2 楼答案
出现此错误的原因是该结果。下一步,当您调用系统时。出来println(result.next)为空。让我们逐行浏览代码:
要回答有关“node=node.next是什么意思”的问题,这意味着引用将“滑动”到下一个节点所在的节点。从LinkedList可视化:
[0]->;[7] ->;空的
-^node^node。下一个
致电后:
[0]->;[7] ->;空的
^node^node。下一个
(编辑:回答评论中的问题:)
在LinkedList上进行迭代通常如下所示: