[英]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.