【问题描述】输入n(n>1)个整数,每次将输入的整数插入到链表头部。-1表示输入结束。
再输入一个整数,在链表中查找该数据并删除对应的节点。
要求输出进行删除操作后链表中所有节点的值。
【输入形式】输入以空格分隔的n个整数,以-1结束输入,再输入一个要删除的整数。
【输出形式】从链表第一个元素开始,输出链表中所有的节点值。以空格分隔。
【样例输入】
2 4 6 7 8 4 -1
2
【样例输出】
4 8 7 6 4
#include<stdio.h>
#include"math.h"
#include"string.h"
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
struct Node *creat()//逆序输入
{
struct Node *head,*p;
while(1)
{
p=(struct Node *) malloc(sizeof(struct Node));
scanf("%d",&p->data);
if(p->data==-1)break;
p->next=head;
head=p;
}
return head;
}
void Display(struct Node *p)
{
while(p)
{
printf("%d ",p->data);
p=p->next;
}
}
struct Node *delete(struct Node * head,int n)
{
struct Node *p1,*p2;
if(head->data==n)
{
p2=head;
head=head->next;
free(p2);
}
p1=head;
p2=head->next;
while(p2!=NULL)
{
if(p2->data==n)
{
p1->next=p2->next;
free(p2);
p2=p1->next;
}
else
{
p1=p2;
p2=p2->next;
}
}
return head;
};
int main()
{
struct Node *head;
head=creat();
//Display(head);
int n;
scanf("%d",&n);
head=delete(head,n);
Display(head);
return 0;
}