链表的构建与排序

来源:互联网 发布:snapgene mac 编辑:程序博客网 时间:2024/06/05 06:56

2.链表的排序:

Description

给出若干个数,将数字存储在链表中,然后使用插入排序,按照升序排列输出数字。

Input

输入一个整数n表示有n个数,接着输入这n个数。

Output

按照升序输出这n个数。

Sample Input

5 3 2 4 5 4

Sample Output

2 3 4 4 5
我没有用插入排序:#include <stdio.h>#include <stdlib.h>#include <malloc.h>typedef struct number{    int m;    struct number *next;}NUM;NUM *CreateList(int n);NUM *Sorting(NUM *head);void PrintList(NUM *head);void FreeList(NUM *head);int main(){    NUM *head;    int n;    scanf("%d", &n);    head = CreateList(n);    head = Sorting(head);    PrintList(head);    FreeList(head);    return 0;}NUM *CreateList(int n){    NUM *head = NULL, *q, *p;    int i;    p = (NUM *)malloc(sizeof(NUM));    head = p;    q = p;    scanf("%d", &q->m);    for(i = 1; i < n; i++)    {        p = (NUM *)malloc(sizeof(NUM));        scanf("%d", &p->m);        q->next = p;        q = p;    }    q->next = NULL;    return head;}NUM *Sorting(NUM *head){    NUM *q = head->next;    NUM *p = head;    //NUM *r;    int t;    if(head->next== NULL)    {        return head;    }    while(p->next != NULL)    {        q = p->next;        while(q != NULL)        {            if(p->m > q->m)            {               t = p->m;               p->m = q->m;               q->m = t;            }            q = q->next;        }        p = p->next;    }    return head;}void PrintList(NUM *head){    NUM *q;    int flag = 1;    q = head;    while(q != NULL)    {        if(flag)        {            printf("%d", q->m);            flag = 0;        }        else            printf(" %d", q->m);        q = q->next;    }    printf("\n");    return;}void FreeList(NUM *head){    NUM *p = head, *q;    while(p != NULL)    {        q = p->next;        free(p);        p = q;    }    return;}


链表的插入排序还不会。

0 0
原创粉丝点击