删除部分代码
void Del_x(LinkList& L, int x) //递归调用删除所有值为x的元素
{
LNode* p;
if (L == NULL)
return;
if (L->data == x)
{
p = L;
L = L->next;
free(p);
Del_x(L, x);
}
else
Del_x(L->next, x);
}
总体代码测试
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
typedef struct LNode
{
int data;
struct LNode* next;
}LNode, * LinkList;
LinkList List_H(LinkList& L) //头插法插入元素
{
LNode* s;
int x;
L = (LinkList)malloc(sizeof(LNode));
L->next = NULL;
printf("请输入链表元素的值(输入-1结束)\n:");
scanf_s("%d", &x);
while (x != -1)
{
s = (LNode*)malloc(sizeof(LNode));
s->next = NULL;
s->data = x;
s->next = L->next;
L->next = s;
scanf_s("%d", &x);
}
return L;
}
void Del_x(LinkList& L, int x) //递归调用删除所有值为x的元素
{
LNode* p;
if (L == NULL)
return;
if (L->data == x)
{
p = L;
L = L->next;
free(p);
Del_x(L, x);
}
else
Del_x(L->next, x);
}
LinkList PrintfList(LinkList L) //打印元素
{
LNode* p;
p = L->next; //p指向第1号元素
if (p == NULL)
printf("NULL");
else
printf("打印链表中的元素:");
while (p != NULL)
{
printf("%d ", p->data);
p = p->next;
}
return L;
}
int main()
{
int x=0;
LinkList L;
L = (LinkList)malloc(sizeof(LNode));
List_H(L);
printf("输入需要删除的元素:");
scanf_s("%d", &x);
Del_x(L, x);
PrintfList(L);
}
测试结果