我在这里学习链接列表,https://practice.geeksforgeeks.org/problems/linked-list-insertion/1#
https://www.geeksforgeeks.org/linked-list-set-2-inserting-a-node/?ref=lbp
在这里,我必须编写两个函数来在链接列表的开头/结尾添加一个节点。
LinkedList: 9->0->5->1->6->1->2->0->5->0 ->0
产出应为:5 2 9 5 6
但是我的输出是:5 2 9
我认为我在函数末尾添加了一个节点是错误的,但是我找不到我的错误。你能告诉我我哪里错了吗?
根据给定的输入文字创建大小为N的链接列表。每个整数输入都附有一个指示器,可以是0,也可以是1。如果是0,则在链接列表的开头插入整数。如果为1,则在链接列表末尾插入整数。提示:在末尾插入时,请确保显式地处理NULL。
示例1:
输入: LinkedList: 9->0->5->1->6->1->2->0->5->0输出:5 2 9 5 6解释:链接列表长度=5 9 0表示应该在开头插入9。修改后的链接列表=9.5 1表示应该在最后插入5。修改后的链接列表=9,5.6 1表示应该在最后插入6。修改后的链接列表=9,5,6.2表示应该在开头插入2。修改后的链接列表=2,9,5,6.5 0表示应该在开头插入5。修改链接列表= 5, 2,9,5,6。最终链接列表= 5,2,9,5,6。
这是我的解决方案:
class Solution
{
//Function to insert a node at the beginning of the linked list.
Node insertAtBeginning(Node head, int x)
{
// code here
Node current = new Node(x);
current.next = head;
head = current;
return head;
}
//Function to insert a node at the end of the linked list.
Node insertAtEnd(Node head, int x)
{
// code here
Node current = head;
while(current.next != null){
current = current.next;
}
Node addthis = new Node(x);
current = addthis;
return head;
}
}
发布于 2021-08-18 05:51:05
实际上,在insertAtEnd()
方法中存在一个问题。您正确地遍历了链接列表的尾部,但您的问题是:
current = addthis;
这将简单地将新节点分配给current
,这不是您想要的。
您想要的是将新节点附加到最后一个节点的next
字段,如下所示:
current.next = addthis;
这样,您实际上将节点添加到列表的前一个元素中。
完整代码:
Node insertAtEnd(Node head, int x) {
Node current = head;
while(current.next != null){
current = current.next;
}
Node addthis = new Node(x);
current.next = addthis;
return head;
}
发布于 2022-11-05 08:30:28
class Solution {
//Function to insert a node at the beginning of the linked list.
Node insertAtBeginning(Node head, int x) {
Node node = new Node(x);
if (head == null) {
head = node;
return head;
}
node.next = head;
head = node;
return head;
}
//Function to insert a node at the end of the linked list.
Node insertAtEnd(Node head, int x) {
Node node = new Node(x);
if (head == null) {
head = node;
return head;
}
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = node;
return head;
}
}
https://stackoverflow.com/questions/68833582
复制相似问题