输入n(n>1)个由小到大的间断正整数,每次将输入的整数插入到链表头部,-1表示结束,在输入一个正整数,在链表中查找并删除该对应的节点,再输入一个正整数,进行比较后插入到该链表之中,再按要求输出进行删除和插入操作之后的所有列表中节点的值。
样例输入 2 3 5 6 9 11 -1
6 8
样例输出 11 9 8 5 3 2
#include<stdio.h>
#include<stdlib.h>
typedef struct a{
int n;
struct a*next;
}x; // 简化结构名
x*cre(){
x*head=NULL,*p;
while(1){
p=(x*)malloc(sizeof(x));
scanf("%d ",&p->n);
if(p->n==-1) break;
p->next=head;
head=p;
}
return head;
} // 链表创建
x*del(x*head,int n){
x*p1,*p2;
if(head->n==n){
p2=head;
head=head->next;
free(p2);
} p1=head;
p2=head->next;
while(p2){
if(p2->n==n){
p1->next=p2->next;
free(p2);
p2=p1->next;
}else
p1=p2;
p2=p2->next;}
return head;
} //链表删除
x *ins(x*head,x*s){
x *p,*p1,*p2;
p2=head;
p=s;
if(!head){
head=p;
head->next=NULL;
}
else{
while((p->n<p2->n )&&(p2->next!=NULL))
{ p1=p2;
p2=p2->next;
} if(p->n>=p2->n){
if(head==p2)
head=p;
else
p1->next=p;
p->next=p2;
}
else{ p2->next=p;
p->next=NULL;
}
}return head;
} //链表插入
void pri(x*p){
while(p){
printf("%d ",p->n);
p=p->next;
}
} //链表遍历
int main(){
x*head,*s;
s=(x*)malloc(sizeof(x));
int n,m;
head=cre();
scanf("%d%d",&n,&s->n);
head=del(head,n);
head=ins(head,s);
pri(head);
return 0;
}