算法 -- 链表插入排序

问题: 这个代码产生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;
}

猜你喜欢

转载自blog.csdn.net/centnetHY/article/details/81185698