当前位置: 代码迷 >> 综合 >> 1398 有序数列
  详细解决方案

1398 有序数列

热度:92   发布时间:2023-12-05 17:53:26.0

1398 有序数列

时间限制 : 2000/1000 MS(Java/Others) | 内存限制 :65536/32768 KB(Java/Others)

提交数 : 1514 | 通过数 : 568

题目描述

有n(n<=100)个整数,已经按照从小到大顺序排列好,现在另外给一个整数x,请将该数插入到序列中,并使新的序列仍然有序。

输入要求

 
 

输入数据由两行组成,第一行是整数n和x,n表示有n个按升序排列的数据,x表示待插入的数据。

第二行是已经按升序排列的n个数的数列。

输出要求

输出插入新的元素后的数列。

输入样例

3 3
1 2 4

输出样例

1 2 3 4

提示

 
 

来源

NBU OJ

代码如下:

#include<stdio.h>
#include<stdlib.h>
typedef struct S{int id;struct S *next;
}stu;
stu* init()
{stu*head=(stu*)malloc(sizeof(stu));head->id=0;head->next=NULL;return head;
}
void endinsert(stu*head,int date)
{stu*p=head;while(p->next!=NULL){p=p->next;}stu*q=(stu*)malloc(sizeof(stu));q->id=date;q->next=p->next;p->next=q;
}
void print(stu*head)
{stu*p=head->next;int flag=0;while(p!=NULL){flag++;if(flag==1)printf("%d",p->id);elseprintf(" %d",p->id);p=p->next;}printf("\n");
}
void paixu(stu*head)
{stu*p=head->next;stu*q=head->next;for(p;p->next!=NULL;p=p->next){for(q=head->next;q->next!=NULL;q=q->next){if(q->id>q->next->id){int temp=q->id;q->id=q->next->id;q->next->id=temp;}}}
}
int main()
{stu*head=init();int n,m;scanf("%d%d",&n,&m);for(int i=0;i<n;i++){int a;scanf("%d",&a);endinsert(head,a);}endinsert(head,m);paixu(head);print(head);}