Description
现在要在一个按顺序已经排好的序列中插入一个数,使它的顺序不会变化
Input
输入数据的第一行有一个整数T,表示有几个数字排列。
第二行是排好的数字。
接下来是你要插入的数。
Output
按顺序排好的数字
Sample Input
9
2 3 5 8 9 10 18 26 32
6
Sample Output
2 3 5 6 8 9 10 18 26 32
#include<stdio.h> #include<stdlib.h> //创建一个结构体储存节点 struct node{ int date; struct node*next; }; int main(){ struct node *p,*head,*q,*t; int n,i,a; scanf("%d",&n); head=NULL;//初始化头节点为空 for(i=1;i<=n;i++){ scanf("%d",&a); p=(struct node*)malloc(sizeof(struct node));//将数据储存在节点的date里 p->date=a; p->next=NULL;//使一个节点中的next指针先指向空 if(head==NULL){//如果是头结点 head=p; } else{ q->next=p;//使上一个节点指向这个节点 } q=p; } scanf("%d",&a);//输入待插入的数 t=head; while(t!=NULL){ if(t->next==NULL||(t->next->date)>a){ p=(struct node*)malloc(sizeof(struct node));//创建一个动态空间来储存这个数据 p->date=a; p->next=t->next; t->next=p; break; } t=t->next; } t=head; while(t!=NULL){ printf("%d ",t->date); t=t->next; } return 0; }