删除节点:输入若干个正整数(输入-1为结束标志)建立一个单向链表
再输入一个整数m,删除链表中值为m的所有结点。试编写相应程序。
#include<stdio.h>
#include<stdlib.h>
struct a //结构a的定义
{
int n;
struct a *next;
} A;
struct a *creat() //建立链表函数
{
int count=1,n;
struct a *p,*tail,*head;
head=tail=NULL;
printf("输入-1结束\n");
while (1)
{
printf("请输入第%d个正整数: ",count);
scanf("%d",&n);
if(n<-1||n==0)
printf("第%d个数输入错误,请重新输入!\n",count);
else if (n==-1)
{
printf("链表输入结束!\n");
break;
}
else
{
p=(struct a *)malloc(sizeof(struct a));
p->n=n;
p->next=NULL;
if(head==NULL)
head=p;
else
tail->next=p;
tail=p;
count++;
}
}
return head;
}
int main ()
{
int m;
struct a *head=NULL,*tail=NULL,*p,*p1,*p2;
head=creat();
printf("输入一个整数m: ");
scanf("%d",&m);
while(head!=NULL && head->n==m) //要删除节点为头结点
{
p2=head;
head=head->next;
free(p2);
}
if(head==NULL) //链表为空则不含任何信息
{
printf("链表中不含任何信息!\n");
return 0;
}
p1=head; //要删除节点不是头结点
p2=p1->next;
while(p2!=NULL)
{
if(p2->n==m)
{
p1->next=p2->next;
free(p2);
}
else
p1=p1->next;
p2=p1->next;
}
printf("删除%d后链表中的信息为:\n",m);
for(p=head;p!=NULL;p=p->next) //遍历链表,输出删除节点后的链表信息
printf("%d ",p->n);
printf("\n");
return 0;
}