-设计一个递归算法,删除不带头结点的单链表L中所有值为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("请输入数值");
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;
}
LinkList List_NoTailInsert(LinkList &L) {
int x;
L=(LinkList)malloc(sizeof(LNode));
LNode *s, *r=L;
printf("请输入数值:\n");
scanf("%d",&x);
L = (LinkList)malloc(sizeof(LNode));
L->data=x;
r=L;
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 delAllX(LinkList &L, int x) {
LNode *p;
if(L==NULL) return;
if(L->data==x) {
p=L;
L=L->next;
free(p);
delAllX(L,x);
} else
delAllX(L->next,x);
}
int main() {
LinkList L=NULL;
List_NoTailInsert(L);
int x;
printf("\n请输入需要删除的数值\n" );
scanf("%d",&x);
delAllX(L,x);
LNode *p = L;
while(p!=NULL) {
printf("%d ",p->data);
p=p->next;
}
return 0;
}
运行效果