java - 在 java geeksforgeeks 中的单链表末尾插入一个节点
问题描述
这是我从 geeksforgeeks 获得的关于在单链表末尾插入节点的代码。第四步没看懂。为什么将 new_node.next 设置为 null,而在创建 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;
}
}
解决方案
是的,这条线:
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
代码末尾的语句也是不必要的。
推荐阅读
- python - 从 pandas 网站读取大型数据集仅返回 1.000 行?
- hadoop - parquet、avro 和其他 hadoop 文件格式的第一行可以有不同的布局吗?
- javascript - 有没有办法在高级 PDF 中打印复选框?(我的意思是复选框本身不是它的价值)
- r - 在一个数据框中的列的百分比中随机乘以一个固定数字
- selenium-webdriver - 有没有办法尽可能多地刷新页面并等待元素在硒中加载到该页面中?
- javascript - 有没有办法在 JavaScript 中跨文件创建全局对象?
- python - 在 python 中写入和分隔单个文本行,由分隔符写入另一个文件的多行
- reactjs - 反应:模块解析失败:意外的令牌
- spring - 配置junit测试时,Spring自动装配环境为空
- php - PHP MySQLi - WHERE“计算值小于”不起作用