#include<stdio.h>
#include<stdlib.h>
#define N 10
typedef struct node{
int data;
struct node* next;
}ElemSN;
//创建一个单向链表
ElemSN* CreatLink(int a[],int n)
{
ElemSN *head,*tail,*p;
head=NULL;
for(int i=0;i<n;i++)
{
p=(ElemSN*)malloc(sizeof(ElemSN));
p->data=a[i];
p->next=NULL;
if(!head)
{
head=tail=p;
tail->next=NULL;
}
else
{
tail=tail->next=p;
tail->next=NULL;
}
}
return head;
}
//删除数据域值为key的结点,并返回头指针
ElemSN* DeleteNode(ElemSN *head,int key)
{
ElemSN *p,*q;
p=head;
while(p)
{
if(p->data-key)
{
q=p;
p=p->next;
}
else
{
if(p-head)
{
q->next=p->next;
free(p);
p=q->next;
}
else
{
head=head->next;
free(p);
p=head;
}
}
}
return head;
}
//打印删除结点后的链表
void PrintLink(ElemSN* head)
{
ElemSN *p=head;
for(;p;p=p->next)
printf("%5d",p->data);
}
int main(void)
{
ElemSN *head;
int key;
int a[N]={3,2,4,8,4,3,6,9,10,3};
printf("请输入需要删除结点的数据域的值:");
scanf("%d",&key); //输入要删除结点的值
head=CreatLink(a,N); //创建单向链表,返回头指针
head=DeleteNode(head,key); //删除数据域值为key的结点,并返回头指针
PrintLink(head); //打印删除结点后的链表
}
链表结点的删除(有无重复值都适用)
猜你喜欢
转载自blog.csdn.net/qq_39241239/article/details/80883598
今日推荐
周排行