有序链表的建立 分类: 链表 2015-06-07 13:21 15人阅读 评论(0) 收藏

数据结构实验之链表六:有序链表的建立

TimeLimit: 1000ms Memory limit: 65536K

题目描述

输入N个无序的整数,建立一个有序链表,链表中的结点按照数值非降序排列,输出该有序链表。

输入

第一行输入整数个数N

第二行输入N个无序的整数。

输出

依次输出有序链表的结点值。

示例输入


6

336 22 9 44 5


示例输出


56 9 22 33 44

#include <bits/stdc++.h>
#define RR freopen("input.txt","r",stdin)
#define WW freopen("ouput.txt","w",stdout)

using namespace std;

struct node
{
    int data;
    node *next;
};

void insret(node *head,node *q)
{
    node *p,*r;
    r=head;
    p=head->next;
    while(p)
    {
        if(q->data<p->data)
        {
            q->next=p;
            r->next=q;
            break;
        }
        p=p->next;
        r=r->next;
    }
    if(!p)
    {
        q->next=p;
        r->next=q;
    }
}

void Output(node *head)
{
    node *p;
    p=head->next;
    while(p)
    {
        if(p!=head->next)
            cout<<" ";
        cout<<p->data;
        p=p->next;
    }
    cout<<endl;
}
int main()
{
    node *head,*q;
    int n;
    head=new node;
    head->next=NULL;
    cin>>n;
    for(int i=1; i<=n; i++)
    {
        q=new node;
        cin>>q->data;
        insret(head,q);
    }
    Output(head);
    return 0;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/juechen/p/4722060.html