飞行的猪哼哼

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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

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

#include <stdio.h>
#include <stdlib.h>
struct node
{
    int data;
    struct node *next;
};
struct node *head;
struct node *creat(int n)
{
    struct node *tail,*p;
    head=(struct node *)malloc(sizeof(struct node));
    head->next=NULL;
    tail=head;
    while(n)
    {
        p=(struct node*)malloc(sizeof(struct node));
        scanf("%d",&p->data);
        p->next=NULL;
        tail->next=p;
        tail=p;
        n--;
    }
    return head;
}

void insert(int v)
{
    struct node *p,*q,*r;
    p=head;
    q=p->next;
    int flag=1;
    r=(struct node *)malloc(sizeof(struct node));
    r->data=v;
    r->next=NULL;
    while(q)
    {
        if(q->data>v)
        {
            p->next=r;
            r->next=q;
            flag=0;
            break;
        }
        else
        {
            p=q;
            q=q->next;
        }
    }
    if(flag)
    {
        p->next=r;
    }
}
void print(struct node *head)
{
    struct node *p;
    p=head->next;
    while(p!=NULL)
    {
        printf("%d",p->data);
        if(p->next!=NULL)
        {
            printf(" ");
        }
        else
        {
            printf("\n");
        }
        p=p->next;
    }
}

int main()
{
    int n,c,v,m;
    struct node *p,*s;
    while(scanf("%d",&n)!=EOF)
    {
        head=creat(n);
        scanf("%d",&c);
        while(c)
        {
            scanf("%d",&m);
            if(m==1)
            {
                scanf("%d",&v);
                insert(v);
            }
            if(m==2)
            {
                print(head);
            }
            c--;
        }
        p=head;
        while(p!=NULL)
        {
            s=p->next;
            free(p);
            p=s;
        }
    }
    return 0;
}

首先强调,每组最后必须释放空间连续建链表会最终导致超内存。 p=head;
while(p!=NULL)
{
s=p->next;
free(p);
p=s;
}
再来想一下,插入函数是如何实现的?
一个遍历指针,一个跟踪指针,必须的,另外插入指针必须,所以需要3个指针。首先把插入指针可以先建全 ,然后跟踪指针指向头结点,遍历指针指向头结点,考虑边境情况,如果插入指针值大于第一个数(遍历指针所指)那么,需要将跟踪指针和插入指针相连,插入指针和遍历指针相连,中间情况相同,考虑另一个边境,也就是遍历指针消失,跟踪指针指向,最后一个节点,此时,如果跟踪指针的值小于插入指针的值,那么,跟踪指针直接和插入指针相连即可。

posted on 2018-08-17 17:30  飞行的猪哼哼  阅读(26)  评论(0)    收藏  举报