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

来源:互联网 发布:怎样在淘宝上联系卖家 编辑:程序博客网 时间:2024/06/04 01:28

Problem Description
输入N个无序的整数,建立一个有序链表,链表中的结点按照数值非降序排列,输出该有序链表。
Input
第一行输入整数个数N;
第二行输入N个无序的整数。
Output
依次输出有序链表的结点值。
Example Input
6
33 6 22 9 44 5
Example Output
5 6 9 22 33 44

#include <stdlib.h>#include <stdio.h>typedef int elemtype;typedef struct lnode{  elemtype data;  struct lnode *next;}sqlist,*linklist;linklist creat(int n){    lnode *p,*tail,*head;    head=new lnode;    head->next=NULL;    tail=head;    for(int i=0;i<n;i++)    {        p=new lnode;        scanf("%d",&p->data);        p->next=NULL;        tail->next=p;        tail=p;    }    return head;}linklist paixu(linklist head){    lnode *p,*q;    p=head->next;    while(p)    {        q=p->next;        while(q)        {            if(p->data>q->data)            {                int t;                t=p->data;                p->data=q->data;                q->data=t;            }            q=q->next;        }        p=p->next;    }    return head;}void output(linklist head){    lnode *p;    p=head->next;    printf("%d",p->data);    p=p->next;    while(p)    {        printf(" %d",p->data);        p=p->next;    }    printf("\n");}int main(){    linklist head;    int n;    scanf("%d",&n);    head=creat(n);    head=paixu(head);    output(head);}
阅读全文
0 0