插入排序

Problem Description

现有 n 个从小到大排列的数组成的序列。需要对这个序列进行 c 次操作。

每次操作有两种类型:

操作 1:插入一个数 v 到序列中,并保持有序。
操作 2:输出当前的序列。
bLue 并不太擅长序列操作,所以他想来请求你的帮助,你能帮助他完成这个任务吗?
Input

输入数据有多组(数据组数不超过 30),到 EOF 结束。

对于每组数据:

第 1 行输入一个整数 n (1 <= n <= 10^5),表示初始的有序序列中数字的个数。
第 2 行输入 n 个用空格隔开的整数 ai (0 <= ai <= 10^6),表示初始序列。
第 3 行输入一个整数 c (1 <= c <= 1000),表示有 c 次操作。
接下来有 c 行,每行表示一次操作:
如果操作类型为 1,则输入格式为 “1 v”,其中 v (0 <= v <= 1000) 表示要插入到序列的数。
如果操作类型为 2,则输入格式为 “2”。
Output

对于每组数据中的每次类型为 2 的操作,输出一行,表示当前的序列,每个数之间用空格隔开。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
struct nod
{
    int data;
    struct nod *next;
};
int main()
{
    int n;
    while(~scanf("%d", &n))
    {
        struct nod *head=(struct nod  *)malloc(sizeof(struct nod));
        head->next=NULL;
        struct nod *mail=head;
        for(int a=0;a<n;a++)
        {
            struct nod *p=(struct nod  *)malloc(sizeof(struct nod));
            p->next=NULL;
            scanf("%d", &p->data);
            mail->next=p;
            mail=p;
        }
        int t;
        scanf("%d", &t);
        while(t--)
        {
            int k;
            scanf("%d",&k);
            if(k==1)
            {
                int kk;
                int top=1;
                scanf("%d", &kk);
                mail=head;
                while(mail->next)
                {
                    if(mail->next->data>kk)
                    {
                        struct nod *p=(struct nod  *)malloc(sizeof(struct nod));
                        p->data=kk;
                        p->next=mail->next;
                        mail->next=p;
                        top=0;
                        break;
                    }
                    else mail=mail->next;
                }
                if(top)
                {
                   struct nod *p=(struct nod  *)malloc(sizeof(struct nod));
                    p->data=kk;
                    p->next=NULL;
                    mail->next=p;
                }
            }
            else if(k==2)
            {
                int top=1;
                mail=head;
                while(mail->next)
                {
                    if(top)top=0;
                    else printf(" ");
                    printf("%d", mail->next->data);
                    mail=mail->next;
                }
                printf("\n");
            }
        }
        while(head)
        {
            mail=head;
            head=head->next;
            free(mail);
        }
    }
    return 0;
}
posted @ 2017-02-09 20:42  Philtell  阅读(149)  评论(0编辑  收藏  举报