gpt4 book ai didi

c++ - 仅通过其地址删除节点,但也会删除其他值,以及如何防止内存泄漏

转载 作者:行者123 更新时间:2023-12-02 10:29:39 24 4
gpt4 key购买 nike

我编写了一个仅按地址删除节点的代码,而deleteNode函数正在删除该位置的节点,但是它删除的是更多值,因此我无法删除最后一个节点。

#include<bits/stdc++.h>
using namespace std;

struct Node { //node defination
int data;
struct Node *next;
Node(int x) {
data = x;
next = NULL;
}
}*head;

Node *findNode(Node* head, int search_for) //find the node that will delete
{
Node* current = head;
while (current != NULL)
{
if (current->data == search_for)
break;
current = current->next;
}
return current;
}


void insert() //insert the values in node
{
int n,i,value;
Node *temp;
scanf("%d",&n);

for(i=0; i<n; i++)
{
scanf("%d",&value);
if(i==0)
{
head=new Node(value);
temp=head;
continue;
}
else
{
temp->next= new Node(value);
temp=temp->next;
temp->next=NULL;
}
}
}

void printList(Node *node) //print the value in node
{
while (node != NULL)
{
printf("%d ", node->data);
node = node->next;
}
cout << endl;
}
void deleteNode(Node *node_ptr);

int main(void) //main starts from here
{

int k,n,value;

{
insert();
scanf("%d",&k);
Node *del = findNode(head, k);
if (del != NULL && del->next != NULL)
{
deleteNode(del);
}
printList(head);
}
return(0);
}
void deleteNode(Node *pos) //delete node function
{
struct Node *temp;
while(temp->next!=0)
{
temp=pos->next;
pos->data=temp->data;
pos->next=temp->next;
pos=temp;
}
}
输入项
5(链表的大小)
1 2 3 4 5( list 元素)
2(删除位置)
预期产量
1 3 4 5
电流输出
1 3 5

最佳答案

创建一个析构函数:

struct Node {                                   //node defination
int data;
struct Node *next;
Node(int x) {
data = x;
next = NULL;
}
~Node() { // destructor
if (next)
delete next;
}
}*head;
因此,删除时,所有节点都将被删除。 deleteNode函数不需要遍历列表:
void deleteNode(Node *pos)                  //delete node function
{
struct Node *temp;

if(pos->next != 0)
{
temp = pos->next;
pos->data = temp->data;
pos->next = temp->next;
temp->next = nullptr; // <- set next to null to avoid next nodes deletion
delete temp; // and delete
}
}
然后在 main中删除头部:
if (head)
delete head;

关于c++ - 仅通过其地址删除节点,但也会删除其他值,以及如何防止内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62839720/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com