在带头结点的单链表L中,删除所有值为x的结点,并释放其空间,假设值为x的结点不唯一//试编写算法以实现上述操作
/插入数据且假设输入10 20 30 30 40 30。bool DeleteList(LinkList* L, int x)//删除。i++)//假设有6个结点。bool Insert_tail(LinkList* L)//插入。bool InitList(LinkList* L)//初始化。bool PrintList(LinkList L)//打印。//指向头结点的指针。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct LNode
{
int data;
struct LNode* next;
}LNode,*LinkList;
bool InitList(LinkList* L)//初始化
{
*L = (LNode*)malloc(sizeof(LNode));
if ((*L) == NULL)
return false;
(*L)->next = NULL;
return true;
}
bool Insert_tail(LinkList* L)//插入
{
LNode* p = *L;
if (p == NULL)
return false;
int i = 0;
int j = 0;
for (i = 0; i < 6; i++)//假设有6个结点
{
LNode* s = (LNode*)malloc(sizeof(LNode));
if (s == NULL)
return false;
scanf("%d", &j);
s->data = j;
p->next = s;
p = s;
}
p->next = NULL;
return true;
}
bool DeleteList(LinkList* L, int x)//删除
{
LNode* p = (*L);
LNode* q = (*L)->next;
if (p == NULL || q == NULL)
return false;
while (q != NULL)
{
if (q->data == x)
{
p->next = q->next;
free(q);
q = p->next;
}
else
{
q = q->next;
p = p->next;
}
}
return true;
}
bool PrintList(LinkList L)//打印
{
LNode* p = L->next;
if (p == NULL)
return false;
while(p != NULL)
{
printf("%d ", p->data);
p = p->next;
}
return true;
}
int main()
{
LinkList L;//指向头结点的指针
InitList(&L); //初始化
Insert_tail(&L);//插入数据且假设输入10 20 30 30 40 30
DeleteList(&L,30);//假设删除30
PrintList(L);//打印测试
return 0;
}
更多推荐




所有评论(0)