有序链表的建立

来源:互联网 发布:开淘宝店投资多少钱 编辑:程序博客网 时间:2024/06/06 00:35

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

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;}


0 0
原创粉丝点击