/*在带头结点的单链表L中,删除所有值为x的结点,并释放其空间,假设值为x的结点不唯一
,试编写算法以实现上述操作*/
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct LNode
{
ElemType data;
struct LNode *next;
}LNode,*LinkList;
LinkList TailCreateList(LinkList &L)
{
L = (LinkList)malloc(sizeof(LNode));
ElemType x;
LNode *r = L;
scanf("%d",&x);
while(x!=9999)
{
LNode *s = (LNode*)malloc(sizeof(LNode));
s->data = x;
r->next = s;
r = s;
scanf("%d",&x);
}
r->next = NULL;
return L;
}
LinkList deleAllVal(LinkList &L,ElemType x)
{
LNode *pre= L;
LNode *p = pre->next;
while(p!=NULL)
{
if(p->data == x)
{
pre->next = p->next;
free(p);
p = pre->next;
}
else{
pre = p;
p = p->next;
}
}
return L;
}
bool printList(LinkList L)
{
LNode *p = L->next;
while(p!=NULL)
{
printf("%d ",p->data);
p = p->next;
}
printf("\n");
return true;
}
void main()
{
LinkList L;
TailCreateList(L);
printList(L);
deleAllVal(L,2);
printList(L);
}
05-28
1270
02-03
1092
01-03
1115