算法:C语言实现 (3)链表的排序

#include <stdlib.h>
#include <stdio.h>

typedef struct node *link;
struct node 
{
    int item;
    link next;
};

/* 初始化一个节点数为n的一个链表*/
void init(link a, int n)
{
    int i;
    for (a, i = 0; i < 9; i++)
    {
        a = (a->next = malloc(sizeof(*a)));
        a->item = rand()%100;
        a->next = NULL;
    }
}

/* 遍历链表*/
void traverse(link p)
{
    while (p != NULL)
    {
        printf("%4d",p->item);
        p = p->next;
    }
    printf("
");
}

int main()
{
    struct node heada, headb;
    link a, b, t;

    //初始化一个头节点
    heada.next = NULL;
    
    a =&heada;
    init(a,9);
    traverse((&heada)->next);

    // headb为排序后的链表的头节点
    headb.next = NULL;
    // 1. 这个地方首先需要遍历需要排序的链表heada
    for (a = (&heada)->next; a != NULL; a = t)
    {
        t = a->next;// 这个地方需要保存a->next ,因为这个连接在下一处就被打断了
        //然后对headb进行遍历
        for (b = &headb; b->next != NULL; b = b->next)
            if (b->next->item > a->item)
                break;
        a->next = b->next;
        b->next = a;
    }
    traverse((&headb)->next);    

    return 0;
}

 主要是它也能正常的运行, 但是不知道为什么这么慢, 9个元素的排序,  应该秒过才是啊!!  看过路过的给个指教呗^_^

原文地址:https://www.cnblogs.com/dLong/p/3395728.html