在带头结点的单链表L中,删除带头结点的单链表L中所有值为x的结点并释放其空间,假设值为x的结点不唯一,试编写算法以实现上述操作
#include<stdio.h>
#include<stdlib.h>
typedef struct LNode {
int data;
struct LNode *next;
} LNode, *LinkList;
LinkList List_TailInsert(LinkList &L) {
int x;
L=(LinkList)malloc(sizeof(LNode));
LNode *s, *r=L;
printf("请输入数值\n");
scanf("%d",&x);
while(x!=9999) {
s=(LNode *)malloc(sizeof(LNode));
s->data = x;
r->next = s;
r=s;
scanf("%d",&x);
}
r->next = NULL;
return L;
}
void del_X_1(LinkList &L, int x) {
printf("\n执行算法dex_X_1\n");
if(L->next==NULL)
return;
LNode *p=L->next,*pre=L,*q;
while(p!=NULL) {
if(p->data==x) {
q=p;
p=p->next;
pre->next=p;
free(q);
} else {
pre=p;
p=p->next;
}
}
}
void del_X_2(LinkList &L, int x) {
printf("\n执行算法dex_X_2\n");
if(L->next==NULL)
return;
LNode *p=L->next,*r=L,*q;
while(p!=NULL) {
if(p->data!=x) {
r->next = p;
r=p;
p=p->next;
} else {
q=p;
p=p->next;
free(q) ;
}
}
}
int main() {
LinkList L=NULL;
int x;
List_TailInsert(L);
printf("\n请输入需要删除的数值\n" );
scanf("%d",&x);
if(L->next==NULL) printf("NULL");
del_X_2(L,x);
LNode *p= L->next;
while(p!=NULL) {
printf("%d ",p->data);
p=p->next;
}
return 0;
}
运行效果
