1429 - C语言-插入队列
已有一个已排好的9个元素的数组,今输入一个数要求按原来排序的规律将它插入数组中。
Input
第一行,原始数列。 第二行,需要插入的数字。
Output
排序后的数列
Examples
Input
1 7 8 17 23 24 59 62 101 50
Output
1 7 8 17 23 24 50 59 62 101
Solution C
#include<stdio.h> #include<malloc.h> #define OK 1 #define ERROR 0 typedef struct Node { int data; struct Node *next; }Node; typedef struct LinkQueue { Node *front; Node *rear; }LinkQueue; int InitQueue(LinkQueue *Q) { Q->front=(Node *)malloc(sizeof(Node)); if(!Q->front) return ERROR; Q->front->next=NULL; Q->rear=Q->front; return OK; } int EnQueue(LinkQueue *Q,int e) { Node *p=(Node *)malloc(sizeof(Node)); if(!p) return ERROR; p->data =e; p->next =NULL; Q->rear->next=p;//插到队尾指针之后 Q->rear=p;//队尾指针后移 return OK; } int Insert(LinkQueue *Q,int e) { Node *p=(Node *)malloc(sizeof(Node)),*q=Q->front; if(!p) return ERROR; p->data =e; while(q!=Q->rear) { if(p->data>=q->data&&p->data<=q->next->data) { p->next=q->next; q->next=p; break; } q=q->next; } return OK; } int Print(LinkQueue *Q) { if(Q->front==Q->rear) return ERROR; Node *p=Q->front; while(p!=Q->rear) { printf("%d\n",p->next->data); p=p->next; } return OK; } int main() { LinkQueue Q; InitQueue(&Q); int a; for(int i=0;i<9;i++) { scanf("%d",&a); EnQueue(&Q,a); } scanf("%d",&a); Insert(&Q,a); Print(&Q); return 0; }
Solution C++
#include<stdio.h> #include<algorithm> using namespace std; int data[10]; int main() { while(scanf("%d",&data[0])!=EOF) { for(int i=1;i<9;i++) scanf("%d",&data[i]); scanf("%d",&data[9]); sort(data,data+10); for(int i=0;i<10;i++) printf("%d\n",data[i]); } return 0; }