有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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);放在句子中,程序将无法编译


共 (2) 个答案

  1. # 1 楼答案

    你想做什么其实并不那么明显

    或许这些评论将有助于:

    // 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。如果不做进一步的工作(例如重写toString()),打印对象引用不会为您提供该对象的val字段

    如果是您的第二个问题,根据上面的评论,是的,您实际上是沿着链接列表移动了一步,因此“result”现在指向您分配的第二个ListNode(contents7

    我不明白你的第三个问题。您已分配了两个ListNode。如果您只需要一个,请执行以下操作:

    result = new ListNode(7);
    
  2. # 2 楼答案

    出现此错误的原因是该结果。下一步,当您调用系统时。出来println(result.next)为空。让我们逐行浏览代码:

    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。下一个

    致电后:

    node = node.next;
    

    [0]->;[7] ->;空的

    ^node^node。下一个

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

    在LinkedList上进行迭代通常如下所示:

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