您好,欢迎来到化拓教育网。
搜索
您的当前位置:首页有序链表的建立 分类: 链表 2015-06-...

有序链表的建立 分类: 链表 2015-06-...

来源:化拓教育网

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

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

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- huatuo9.cn 版权所有 赣ICP备2023008801号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务