定义结构体:
#include<stdio.h>
#include<malloc.h>
typedef struct _STU
{
int id;
struct _STU* next;
}STU,*PSTU;
头插
void Inserthead(PSTU* phead,int id)
{
PSTU pnew = (PSTU)malloc(sizeof(STU));
pnew->id = id;
pnew->next = *phead;
*phead=pnew;
}
尾插
void Inserttail(PSTU* phead,int id)
{
if (*phead == NULL)
{
Inserthead(phead, id);
}
else
{
PSTU ppos = *phead;
while (ppos->next != NULL)
{
ppos = ppos->next;
}
PSTU pnew = (PSTU)malloc(sizeof(STU));
pnew->id = id;
pnew->next = NULL;
ppos->next = pnew;
}
}
头删
void Deletehead(PSTU* phead)
{
if (*phead != NULL)
{
PSTU ppos = *phead;
*phead = ppos->next;
free(ppos);
ppos = NULL;
}
}
先删除与该值相同的第一个数
PSTU Deletefirstvalue(PSTU ppos, int id)
{
while (ppos->next != NULL&&ppos->next->id != id) //当链表不是一个结点并且头指针的next的id 不等于id时,往后循环
{
ppos = ppos->next;
}
if (ppos->next != NULL)
{
PSTU t = ppos->next;
ppos->next = t->next;
free(t);
t = NULL;
return ppos;
}
else
{
return NULL;
}
}
删除值函数
void Deletebyvalue(PSTU *phead,int id)
{
while ((*phead)->id==id)
{
Deletehead(phead); //当头指针的id和输入i的d相同时,删除头指针
}
PSTU ppos = *phead; //让位置指向头指针
ppos=Deletefirstvalue(ppos,id);//删除第一个与它相同的id,让位置停留在已删id的前一位
while (ppos != NULL) //继续找下一个不为空的地址
{
ppos=Deletefirstvalue(ppos, id); //调用函数,每次让位置停留在已删id的前一位
}
}
输出函数
void show(const PSTU phead)
{
PSTU ppos = phead;
while (ppos != NULL)
{
printf("%d,\n", ppos->id);
ppos = ppos->next;
}
}
主函数
int main()
{
PSTU head1 = NULL; PSTU head2 = NULL;
Inserttail(&head1, 1);
Inserttail(&head1, 2);
Inserttail(&head1, 10);
Inserttail(&head1, 8);
Inserttail(&head1, 9);
/*PSTU ppos = head1;
Deletebyvalue(&head1,1);*/ // 单链表head1时,删除链表中与1相同的元素
Inserttail(&head2, 1);
Inserttail(&head2, 2);
Inserttail(&head2, 9);
Inserttail(&head2, 3);
Inserttail(&head2, 5);
PSTU ppos = head2;
while (ppos!= NULL)
{
Deletebyvalue(&head1,ppos->id); //删除与链表1中与链表2相同的id
ppos = ppos->next;
}
show(head1);
return 0;
}