繁体   English   中英

java geeksforgeeks 在单向链表的末尾插入一个节点

[英]inserting a node at the end of a singly linked list in java geeksforgeeks

这是我从 geeksforgeeks 获得的关于在单向链表末尾插入节点的代码。 我不明白第四步。 为什么它使 new_node.next 为空,当它在创建 new_node 时没有初始化时首先应该是空的?

// Linked List Class 
class LinkedList 
{ 
    Node head;  // head of list 
  
    /* Node Class */
    class Node 
    { 
        int data; 
        Node next; 
           
        // Constructor to create a new node 
        Node(int d) {data = d; next = null; } 
    } 


    /* Appends a new node at the end.  This method is  
       defined inside LinkedList class shown above */
    public void append(int new_data) 
    { 
        /* 1. Allocate the Node & 
           2. Put in the data 
           3. Set next as null */
        Node new_node = new Node(new_data); 
      
        /* 4. If the Linked List is empty, then make the 
               new node as head */
        if (head == null) 
        { 
            head = new Node(new_data); 
            return; 
        } 
      
        /* 4. This new node is going to be the last node, so 
             make next of it as null */
        new_node.next = null; 
      
        /* 5. Else traverse till the last node */
        Node last = head;  
        while (last.next != null) 
            last = last.next; 
      
        /* 6. Change the next of last node */
        last.next = new_node; 
        return; 
    } 
}

是的,线路:

new_node.next = null;

是不必要的。 事实上,就连评论也证明了这一点。 步骤#3 注释和第二步#4 注释解释了相同的操作,没有做前者就没有办法做后者。

另一个不必要的步骤,一个更重要的步骤,首先被@DaveNewton 注意到,而我却错过了。 线路:

head = new Node(new_data); 

当列表为空时发生,应该是:

head = new_node;

防止对Node对象进行额外的无用分配。 可选地,该行:

Node new_node = new Node(new_data); 

可以移动到if块下方,但这会不必要地重复代码(但不是努力)。

代码最后的return语句也是不必要的。

暂无
暂无

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

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