创建了一个链表,但如何删除 c++ 中的"所有"节点

Created a linked list, but how to delete 'all' the nodes in c++

本文关键字:删除 c++ 中的 何删除 节点 所有 一个 链表 创建      更新时间:2023-10-16

我写了以下代码来创建链表。所以,我想知道如何删除链表的所有节点。我还想知道我创建节点并将元素插入其中的方式是正确的。

struct node
{
int val;
node *next;
};
int main()
{
node *head, *temp;
cout << "enter no of elements" << endl;
int n;
cin >> n;
//=============Creating Nodes And Inserting Elements===========//
for(int i = 0; i < n; i++)
{
cout << "enter the element in " << i << "th node" << endl;
if(i == 0)
{
temp = new node(); 
cin >> temp->val; 
head = temp;
}
else
{
temp->next=new node();
temp=temp->next;
cin >> temp->val;
}
}
temp->next=NULL;
//===================Deleting all the nodes=================//

return 0;
}

您可以通过多种方式创建链表,我将向您展示一种方法:

结构:

struct linkedList {
int data;         // store data
linkedList *next; // store a pointer to the next node
} *head; // "head" is a pointer points to the first node

以下函数是创建新节点的简单方法:

void InsertNode(int data){
linkedList *node = new linkedList;
node->data = data;
node->next = head;
head = node;
}

当您要删除链表中的所有节点时:

void deleteAllNodes(){
linkedList *temp = head, *next;
while(temp != NULL){
next = temp->next;
delete temp;
temp = next;
}
delete head;
head = NULL;
}

如果有什么不清楚的评论。

通过浏览列表delete所有节点:

node *temptemp;      // tempory variable to store
// the next list nodes address
for (temp = head;    // begin at the head of the list
temp;           // as long as temp != NULL
temp = temptemp // the temp->next we stored in the loops body
) {
temptemp = temp->next;  // remember temp->next cause
delete temp;            // next is gone now.
}

use 析构函数

struct node
{
~node()
{
if (NULL != next)
{
delete next;
}
}
int val;
node *next = NULL; //initialize with NULL
};

现在从主删除头节点

int main()
{
...
delete head;
...
}

最明显的问题是为什么要创建自己的列表而不是使用 STL 中的内容,例如std::list?编码方式更像是 C 而不是C++。添加、删除等节点的方法应该是节点结构的成员函数。例如:

struct node
{
int val;
node *next;
explicit node(int val = 0) : val{val}, next{nullptr} {}
void add_node(node *nodep) {
node *tail = this;
while (tail->next != nullptr)
tail = tail->next;
tail->next = nodep;
}
~node() {
delete next;
}
};

但是使用 STL 中的容器确实是最好的。