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

qq_29025081 2016-10-16 04:51:08
# 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;
}
}
...全文
97 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
paschen 2016-10-16
  • 打赏
  • 举报
回复
你这一部分: if(flag) { delete_list(L_1,flag); cout<<"存在这个一个数并且已经被删除!"<<endl; cout<<"现在链表L_1:"<<endl; print(L_1); } 你已经删除了,又去print(L_1); ,该函数中使用已经释放了指针,故出错
qq_29025081 2016-10-16
  • 打赏
  • 举报
回复
我自己 发现了 野指针了。。。。。。。
qq_29025081 2016-10-16
  • 打赏
  • 举报
回复
主函数中if中的 delete_list函数存在问题

69,374

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧