[英]c++ Append to linked list
I'm writing a piece of code to append a node to the end of a singly linked list, but it seems that it doesn't append anything at all. 我正在编写一段代码将一个节点附加到单链表的末尾,但它似乎根本没有附加任何内容。 Can anybody give me some idea of what I'm doing wrong?
谁能让我知道我做错了什么?
#include<iostream>
using namespace std;
struct Node{
int val;
Node* next;
Node(int v) : val(v), next(NULL) {}
};
void append(Node &head, int d){
Node n = head;
while(n.next != NULL){
n = *n.next;
}
Node end(d);
n.next = &end;
}
int main(){
Node head(0);
for(int i=1;i<5;i++){
append(head, i);
}
Node n = head;
while(n.next != NULL){ //print the linked list, result is 0
cout << n.val<<" ";
n = *n.next;
}
cout<<n.val<<endl;
return 0;
}
EDIT: I changed the append() method to append a dynamically-allocated node each time, but it still doesn't work. 编辑:我改变了append()方法,每次都附加一个动态分配的节点,但它仍然不起作用。
void append(Node &head, int d){
Node n = head;
while(n.next != NULL){
n = *n.next;
}
Node* end = new Node(d);
n.next = end;
}
You append the local object Node end(d);
附加本地对象
Node end(d);
to the end of the linked list. 到链表的末尾。 This object is destroyed upon exist from
append
and the last list element points to a non-existent object. 这个对象在
append
存在时被销毁,最后一个列表元素指向一个不存在的对象。
A few issues with this. 这个问题有些问题。
You make a copies in your append
function here Node n = head;
你在你的
append
函数中复制Node n = head;
and here n = *n.next
. 这里
n = *n.next
。 You then then finally make a change to the copy rather than the original. 然后,您最后更改副本而不是原始副本。
You are assigning Node end(d)
on the stack. 您正在堆栈上分配
Node end(d)
。 When append
returns it goes out of scope and is deleted. 当
append
返回时,它超出范围并被删除。
You can fix both with, 你可以修复两个,
#include<iostream>
#include <memory>
using namespace std;
struct Node{
int val;
std::shared_ptr<Node> next;
Node(int v) : val(v), next(nullptr) {}
};
void append(Node &head, int d){
Node* n = &head;
while(n->next != nullptr){
n = n->next.get();
}
n->next = std::make_shared<Node>(d);
}
int main(){
Node head(0);
for(int i=1;i<5;i++){
append(head, i);
}
Node n = head;
while(n.next != nullptr){
cout << n.val<<" ";
n = *n.next;
}
cout<<n.val<<endl;
return 0;
}
For the edited Question: You are copying the head
to n
, then modify n
. 对于编辑过的问题:您正在将
head
复制到n
,然后修改n
。 At the end of your append
function, n
is destroyed, but head
was never touched. 在你的
append
函数结束时, n
被销毁,但是从未触及过head
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.