如果我们不创建一个新节点并使用指针插入数据并建立链接(在链表中)怎么办?

What if we don't create a new node and use a pointer to insert data and make links instead (in linked list)?

本文关键字:建立 数据 插入 指针 链接 怎么办 链表 我们 一个 新节点 如果      更新时间:2023-10-16

我试图使用结构和类实现链表的基本操作,但我通常会搞砸一些东西。我对这里的内存分配感到困惑。例如,为什么此程序无法正常工作?

#include<iostream>
using namespace std;
struct node{
int data;
node* link;
};
node* head;
void insert(int x){
node temp;
temp.data = x;
temp.link = head;
head = &temp;
}
void print_list(){
node* temp = head;
cout<<"The list is:n";
while(temp!=NULL){
cout<<temp->data<<" ";
temp = temp->link;
}
}
int main(){
head = NULL;
cout<<"How many numbers?n";
int n;
cin>>n;
while(n--){
cout<<"nEnter value:n";
int value;
cin>>value;
insert(value); // This function inserts node at beginning of the list
print_list();
}
return 0;
}

但是如果我将插入功能更改为此功能,它可以工作

void insert(int x){
node* temp = new node();
temp->data = x;
temp->link = head;
head = temp;
}

另外,有人可以推荐我一个学习链表,树和图表的好网站吗?

void insert(int x){
node temp;
temp.data = x;
temp.link = head;
head = &temp;
}

对象具有生存期,在函数上方的函数中,由变量表示的对象temp在调用函数时创建,在函数退出时销毁。

head指向的是这个物体。换句话说,一旦这个函数被退出,head就会指向一个已被销毁的对象。C++不会仅仅因为有东西指向物体而使它保持活力。这就是您的程序不起作用的原因。

现在看看你的工作代码

void insert(int x){
node* temp = new node();
temp->data = x;
temp->link = head;
head = temp;
}

现在,temp指向的对象已使用new创建。由new创建的对象在被删除之前一直存在。因此,在这种情况下,当函数退出时,对象仍然存在。所以代码有效。

所有这些都将在任何一本关于C++的半体面的书中解释。如果你想正确地学习C++,你真的应该买一本好书。