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

来源:互联网 发布:如何关闭端口号 编辑:程序博客网 时间:2024/05/02 21:15

题目描述

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

输入

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

输出

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

示例输入

6
33 6 22 9 44 5

示例输出

5 6 9 22 33 44

提示

不得使用数组!

来源

思路:单向递增链表,向链表中加元素要考虑

1.比首元素小,放在首元素之前。

2.比末尾元素大,放在之后。

3.插入中间。

//#include <bits/stdc++.h>#include <iostream>#include <cstdio>#include <cstdlib>#include <cmath>#include <cstring>#include <string>#include <stack>#include <set>#include <queue>#include <algorithm>#define CLR(a, b) memset(a, (b), sizeof(a))#define INF 0x3f3f3f3f#define eps 1e-8typedef long long LL;using namespace std;typedef struct Node{    int date;    struct Node *next;}node;int main(){   #ifdef LOCAL     freopen("E://in.txt","r",stdin);   #endif // LOCAL    int n;    while(~scanf("%d",&n))    {        node *head=(node *)malloc(sizeof(node));        head->next=NULL;        node *pr=head;        for(int i=0;i<n;i++)        {            int date;            scanf("%d",&date);            if(i==0)            {                pr->date=date;//添加第一个元素            }            else            {                node *p=(node *)malloc(sizeof(node));                p->date=date;                p->next=NULL;                if(p->date<head->date)//判断要新加入的元素和头元素的大小关系                {                    p->next=head;                    head=p;                }                else                {                    node *pr=head;                    int flag=0;                    while(pr->next)                    {                        node *r=pr->next;                        if(r->date>p->date)                        {                            pr->next=p;                            p->next=r;                            flag=1;                            break;                        }                        pr=pr->next;                    }                    if(flag==0)//没有插入,所以放在最后。                    {                        pr->next=p;                    }                }            }        }        pr=head;        while(pr->next)//打印链表        {            printf("%d ",pr->date);            pr=pr->next;        }        printf("%d\n",pr->date);    }    return 0;}
0 0
原创粉丝点击