用递归算法删除不带头结点的单链表中值为x的数
#include
#include
#include
typedef struct lnode
{
int data;
struct lnode *next;
}linknode;
linknode*Create(linknode*l,int n)
{
int i;
l=(linknode*)malloc(sizeof(lnode));
scanf("%d",&l->data);
l->next=NULL;
linknode*r=l;//注意出现断链的情况,伪代码可以出现,但在写入程序执行时,必须避免断链情况的发生//
for(i=1;i"%d",&p->data);
p->next=NULL;
r->next=p;
r=p;
}
return l;
}
linknode*Del_x(linknode*l,int x)
{
linknode*p;
if(l==NULL) return l;
if(l->data==x)
{
p=l;
l=l->next;
free(p);
Del_x(l,x);
}
else
{
l=l->next;
Del_x(l,x);
}
}
void Print(linknode*l)
{
linknode*p=l;
while(p!=NULL)
{
printf("%d\t",p->data);
p=p->next;
}
}
int main()
{
linknode*L;
int n,x;
scanf("%d",&n);
L=Create(L,n);
scanf("%d",&x);
Del_x(L,x);
Print(L);
}
这是怎么回事,为什么运行出来这么多
p=l;
l=l->next;
free(p);
你这删除节点的代码是错误的
看这里
a=>b=>c
现在你要删除b节点,那你要把a->next指向c,把b跳过去,然后删除b
你没有执行这个操作,就直接把指针跳走了,然后就free了节点,那被free的节点就变成野指针了,你链表里中间一项是个野指针,它指向哪都有可能,而大概率它的next不太可能正好是个NULL,于是就再也停不下来了
数据结构对单链表进行数据排序 http://bbs.csdn.net/topics/392201633
你的问题是链表一旦删除节点,整个链就断了。你的代码适合用固定头结点的链表,修改如下,可以运行
#include<stdio.h>
#include<stdlib.h>
typedef struct lnode
{
int data;
struct lnode *next;
}linknode;
linknode*Create(linknode*l,int n)
{
int i;
l=(linknode*)malloc(sizeof(lnode));
l->next=NULL;
linknode*r=l;//注意出现断链的情况,伪代码可以出现,但在写入程序执行时,必须避免断链情况的发生//
for(i=0;i<n;i++)
{
linknode*p=(linknode*)malloc(sizeof(lnode));
scanf("%d",&p->data);
p->next=NULL;
r->next=p;
r=p;
}
return l;
}
linknode*Del_x(linknode*l,int x)
{
linknode*p;
if(l->next==NULL) return l;
if(l->next->data==x)
{
p=l->next;
l->next = p->next;
free(p);
Del_x(l,x);
}
else
{
l=l->next;
Del_x(l,x);
}
}
void Print(linknode*l)
{
linknode*p=l->next;
while(p!=NULL)
{
printf("%d\t",p->data);
p=p->next;
}
}
int main()
{
linknode*L = NULL;
int n,x;
scanf("%d",&n);
L=Create(L,n);
scanf("%d",&x);
Del_x(L,x);
Print(L);
}