插入排序SDUT

插入排序
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 的操作,输出一行,表示当前的序列,每个数之间用空格隔开。

Sample
Input
5
1 2 2 3 5
5
1 0
2
1 3
1 7
2
Output
0 1 2 2 3 5
0 1 2 2 3 3 5 7

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node
{
    int data;
    struct node *next;
} node;
node *creat(int n)
{
    node *head,*p,*tail;
    head=(node *)malloc(sizeof(node));
    head->next=NULL;
    tail=head;
    while(n--)
    {
        p=(node *)malloc(sizeof(node));
        scanf("%d",&p->data);
        p->next=NULL;
        tail->next=p;
        tail=p;
    }
    return head;
}
node * output(node *head)
{
    node *p;
    p=head->next;
    if(p!=NULL)
    {
        while(p)
        {
            if(p->next==NULL)
                printf("%d\n",p->data);
            else
                printf("%d ",p->data);
            p=p->next;
        }
    }
    return head;
}
void fre(node *head)
{
    node *p,*q;
    p=head;
    while(p)
    {
        q=p->next;
        free(p);
        p=q;
    }
}

node *ins(node *head, int v)
{
   node *p,*q;
   p=(node *)malloc(sizeof(node));
   p->data=v;
   p->next=NULL;
   q=head;
   while(q->next!=NULL)
   {
       if(q->next->data>p->data)
       {
          break;
       }
       else  q=q->next;
   }
   p->next=q->next;
   q->next=p;
   return head;
}
int main()
{
    int n,c,m,v;
    while(~scanf("%d",&n))
    {
        node *head;
        head=creat(n);
        scanf("%d",&c);
        while(c--)
        {
            scanf("%d",&m);
            if(m==1)
            {
                scanf("%d",&v);
                ins(head,v);
            }
            if(m==2)
                output(head);
        }
        fre(head);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值