英文:
Why is new Node is not added?
问题
public class LinkedList {
static Node head;
static class Node {
int data;
Node next;
Node(int dat) {
data = dat;
next = null;
}
}
public void add(int data) {
Node node = new Node(data);
Node n = head;
while (n != null) {
n = n.next;
}
n = node;
}
public void print() {
Node n = head;
while (n != null) {
System.out.println(n.data);
n = n.next;
}
}
}
我注意到在add()
方法中,我将'node'
赋值给一个具有null
值的项,但是,疑问的是,即使n.next
变为null
,它仍然是一个节点,对吗?因为'next'
被定义为一个Node
,所以应该可以正常工作。
英文:
public class LinkedList {
static Node head;
static class Node{
int data;
Node next;
Node(int dat){
data = dat;
next = null;
}
}
public void add(int data){
Node node = new Node(data);
Node n = head;
while (n!= null){
n = n.next;
}
n = node;
}
public void print(){
Node n = head;
while(n!=null){
System.out.println(n.data);
n = n.next;
}
}
}
I realize that in the add() method I am assigning 'node' to an item that has the value null, however, the doubt is even is n.next becomes null its still a node right because 'next' is defined as a Node, so it should work right.
答案1
得分: 3
要在链表末尾添加新节点,需要执行以下步骤:
- 创建新节点。
- 检查链表是否为空。如果为空,将
head
指向新节点并从函数返回。 - 如果链表不为空,遍历链表直到到达最后一个节点。
- 将最后一个节点的
next
指向步骤 1 中创建的新节点。
问题
您的代码中存在一些问题:
- 您没有处理在空链表中添加新节点的特殊情况。
add()
方法中的while
循环在到达最后一个节点时不会停止。它只有在n
本身变为null
时才会停止,这意味着您无法将新节点添加到链表中。
解决方案
您需要将 while
循环中的条件从
n != null
改为
n.next != null
以确保在循环结束后您位于链表中的最后一个节点,然后要在链表中添加新节点,您需要将最后一个节点的 next
指向新节点:
n.next = node;
您的 add()
方法应编写为:
public void add(int data) {
Node node = new Node(data);
if (head == null) {
head = node;
return;
}
Node n = head;
while (n.next != null){
n = n.next;
}
n.next = node;
}
英文:
To add the new node at the end of the linked list, you need to take following steps:
- Create the new node
- Check if linked list is empty. If it is, point the
head
to the new node and return from the function - If linked list is not empty, traverse the linked list until the last node is reached
- Point the
next
of the last node to the new node created in step 1.
<h3>Problem</h3>
There are couple of problems in your code:
- You are not handling the special case of adding the new node in the empty linked list
while
loop in theadd()
method doesn't stops when the last node is reached. It only stops whenn
itself becomesnull
which means you cannot add the new node in the linked list
<h3>Solution</h3>
You need to change the condition in the while
loop from
n != null
to
n.next != null
to make sure that you are at the last node in the linked list after the loop ends and then to add the new node in the linked list, you need to point the next
of the last node to the new node
n.next = node;
Your add()
method should be written as:
public void add(int data) {
Node node = new Node(data);
if (head == null) {
head = node;
return;
}
Node n = head;
while (n.next != null){
n = n.next;
}
n.next = node;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论