要对一个链表的一个数删除 结果那个数指向的下个指针变成NULL

C语言 码拜 7年前 (2017-04-16) 889次浏览
# include <stdio.h>
# include <malloc.h>
# include <iostream>
# include <stdlib.h>
using namespace std;
# define OK 1
typedef int status;
typedef int Elemtype;
typedef struct LNode
{
Elemtype data;
LNode *next;
}*L,LL;
status init_list(L &LK);
status insert_list(L LK,int num_ins);
status search_list(L LK,int num_s);
status delete_list(L LK, int pos);
void print(L LK);
int main()
{
int i,j,num,flag;
L L_1,L_2;
init_list(L_1);       //*
init_list(L_2);
for(i=0;i<5;i++)
{
insert_list(L_1,i);
}
for(j=3;j<7;j++)
{
insert_list(L_2,j);
}
cout<<“当前链表L_1:”<<endl;
print(L_1);
cout<<“当前链表L_2:”<<endl;
print(L_2);
cout<<“输入一个你想要在L_1中搜索的数字:\n”<<endl;
cin>>num;
flag = search_list(L_1,num);
cout<<flag<<endl;
if(flag)
{
delete_list(L_1,flag);
cout<<“存在这个一个数并且已经被删除!”<<endl;
cout<<“现在链表L_1:”<<endl;
print(L_1);
}
return 0;
}
status init_list(L &LK)
{
LK = (L)malloc(sizeof(LNode));
if(LK == NULL )
{
cout<<“Error!”<<endl;
exit(-1);
}
LK->next = NULL;
return OK;
}
status insert_list(L LK,int num_ins)
{
L L_new;  //L_temp;
L_new = (L)malloc(sizeof(LNode));
L_new->data = num_ins;
//L_temp = LK;
L_new->next = LK->next;
LK->next = L_new;
return OK;
}
status search_list(L LK,int num_s)
{
int i = 1;
L LK_1 = LK;
while(LK_1!=NULL)
{
if(LK_1->next->data == num_s)
break;
LK_1 = LK_1->next;
i++;
}
return i;
}
status delete_list(L LK, int pos)
{
L LK_1 = LK;
L p;
for(int i=0;i<pos;i++)
{
if(LK_1!=NULL)
LK_1 = LK_1->next;
else
{
cout<<“Error!”<<endl;
return 0;
}
}
p = LK_1->next;
LK_1 = LK_1->next->next;
free(p);
return OK;
}
void print(L LK)
{
LK = LK->next;
while(LK)
{
cout<<LK->data<<endl;
LK = LK->next;
}
}
解决方案

60

你这一部分:
if(flag)
{
delete_list(L_1,flag);
cout<<“存在这个一个数并且已经被删除!”<<endl;
cout<<“现在链表L_1:”<<endl;
print(L_1);
}
你已经删除了,又去print(L_1); ,该函数中使用已经释放了指针,故出错

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明要对一个链表的一个数删除 结果那个数指向的下个指针变成NULL
喜欢 (0)
[1034331897@qq.com]
分享 (0)