gpt4 book ai didi

c++ - Segmentation Fault 删除节点

转载 作者:行者123 更新时间:2023-11-28 06:16:32 24 4
gpt4 key购买 nike

我有一个只操作基本链表的 C++ 代码——添加一个新节点、删除一个节点并查看列表

//UNIX Environment
#include <iostream>
#include <malloc.h>
#include <stdlib.h>
#include <stdio.h>
#define clear() printf("\033[H\033[J")
using namespace std;

struct node
{
int val;
node *next;
};

struct node* head = NULL;

void add_node(struct node *hea)
{
char f;
int val;
cout<<"Enter value : ";
cin>>val;
if(head==NULL)
{
head = new(struct node);
head->val = val;
head->next = NULL;
}
else
{
node *traverser = hea;
node *traverser_prev = NULL;
while(traverser!=NULL)
{
traverser_prev = traverser;
traverser=traverser->next;
}
traverser = new(struct node);
traverser->val = val;
traverser->next = NULL;
traverser_prev->next=traverser;
}
cout<<"\nEnter Y to return : ";
cin>>f;
while(f!='Y')
{
cout<<"Wrong entry.Enter again : ";
cin>>f;
}
return;
}

void view_list(struct node *hea)
{
char f;
node *traverser = hea;
while(traverser!=NULL)
{
cout<<traverser->val<<" ";
traverser=traverser->next;
}
cout<<"\nEnter Y to return : ";
cin>>f;
while(f!='Y')
{
cout<<"Wrong entry.Enter again : ";
cin>>f;
}
return;
}

void delete_node(node *hea)
{
char f;
int del_value;
cout<<"Enter value to be deleted :";
cin>>del_value;

node *traverser = hea;
cout<<"OK1\n";
node* traverser_prev = NULL;
cout<<"OK2\n";

while(traverser!=NULL)
{
if(traverser->val==del_value)
{
if(traverser==hea)
{
hea=traverser->next;
cout<<"Here cond1\n";
delete traverser;
}
else
{
traverser_prev->next = traverser->next;
cout<<"Here cond2\n";
}
}
else
{
traverser_prev = traverser;
traverser = traverser->next;
cout<<"Here cond3\n";
}
}
cout<<"\nEnter Y to return : ";
cin>>f;
while(f!='Y')
{
cout<<"Wrong entry.Enter again : ";
cin>>f;
}
return;
}
int main(int argc, char* argv[])
{
while(1)
{
clear();
int choice;
cout<<"POINTER BASICS\n";
cout<<"1. Add new element\n";
cout<<"2. View elements\n";
cout<<"3. Delete element\n";
cout<<"4. Exit\n";
cout<<"Enter choice: ";
cin>>choice;
switch(choice)
{
case 1: add_node(head);
break;
case 2: view_list(head);
break;
case 3: delete_node(head);
break;
default:break;
}
if(choice==4)
break;
}
}

但是,每当我尝试删除节点时,它都会抛出一个带有核心转储的段错误。错误原因是什么?

最佳答案

一个 问题是,在delete_node 函数中,您按值 传递列表头,这意味着指针被复制并在功能你只修改拷贝。

有两种解决方案:要么根本不使用参数,只使用全局变量,要么通过引用传递参数:

void delete_node(node*& hea)

关于c++ - Segmentation Fault 删除节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30185183/

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