1. 程式人生 > >演算法 -- 連結串列插入排序

演算法 -- 連結串列插入排序

問題: 這個程式碼產生0 ~ 999之間的N個隨機數,構建每個節點代表一個數的連結串列,然後重新排列這些節點,使之按照順序出現。

 

分析:

  • 1、b連結串列為空時,  x = b;       x->next = NULL;    t->next = NULL;   x->next = t;

                           

  • 2、待插入的數比已連線上的數小    即走到break;  退出迴圈   t->next = x->next;  x->next = t;

       

  • 3、待插入的數比已連線上的數大  ,即走到 x->next = NULL; 自動退出迴圈  t->next = x->next = NULL; x->next = t;

      

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

typedef struct node *link;

struct node
{
    int     item;
    link    next;
};

int N;

void test_print(link head)
{
    int i;
    link p = head;

    for (i = 1; i < N + 1; i++)
    {   
        printf("%d ", p->item);
        p = p->next;
    }   
    printf("\n");
}

int main(int argc, const char *argv[])
{
    int i;
    struct node heada, headb;  
    link t, u, x, a = &heada, b;

    if (argc != 2)
    {   
        printf("Usage: a.out <N>\n");
        return -1; 
    }   

    N = atoi(argv[1]);

    // 建立連結串列並填充資料
    for (i = 0, t = a; i < N; i++)
    {   
        t->next = malloc(sizeof *t);
        t = t->next;
        t->next = NULL;
        t->item = rand() % 1000;
    }   
    test_print(heada.next);

    // 執行排序插入
    b = &headb;
    b->next = NULL;
    for (t = a->next; t != NULL; t = u)
    {   
        u = t->next;
        for (x = b; x->next != NULL; x = x->next)
            if (x->next->item > t->item)
                break;
        t->next = x->next;
        x->next = t;
    }

    test_print(headb.next);

    return 0;
}