【问题标题】:inserting a node at the end of a singly linked list in java geeksforgeeks在 java geeksforgeeks 中的单链表末尾插入一个节点
【发布时间】:2021-01-06 11:50:27
【问题描述】:

这是我从 geeksforgeeks 获得的关于在单链表末尾插入节点的代码。第四步没看懂。为什么 new_node.next 在创建 new_node 时未初始化时应该为 null?

// 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; 
    } 
}

【问题讨论】:

  • 顺便说一下,第二块代码的顶部被切掉了一点到阴影块的外面。
  • 我打算重新格式化代码,但它比没有正确缩进更糟糕。我认为append 方法在LinkedList 类定义之外,但应该在其中。 - 但我不确定我是否应该修复它。
  • 我同意你的看法@qwerty。我认为分配是不必要的。
  • @querty - 您需要缩进所有代码,以便其格式正确。 “{}”工具将为您做到这一点。
  • 末尾的return 也是不必要的。 - 并且有两个步骤#4s

标签: java singly-linked-list


【解决方案1】:

是的,行:

new_node.next = null;

是不必要的。事实上,即使是 cmets 也见证了这一点。第 3 步注释和第 4 步注释说明了相同的操作,如果不执行前者,则无法执行后者。

@DaveNewton 首先注意到了另一个不必要的步骤,一个更重要的步骤,但我错过了。行:

head = new Node(new_data); 

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

head = new_node;

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

Node new_node = new Node(new_data); 

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

代码末尾的return 语句也是不必要的。

【讨论】:

  • 应该是不太熟悉java的人写的吧
猜你喜欢
  • 2020-11-15
  • 2015-02-08
  • 1970-01-01
  • 2015-12-14
  • 2011-08-13
  • 2016-10-11
相关资源
最近更新 更多