链表排序算法

自己写的的一个链表排序,针对的是一个无序的链表。基本思路是将旧链表的节点一个一个分离并按顺序插入另一个链表,然后将就链表表头指向新链表。


#include<stdio.h>


typedef struct node Node;
struct node
{
    int num;
    Node *next;
};

//生成一个新节点
Node *creat_node(void)
{
    Node *new_node = (Node *)malloc(sizeof(Node));
    if(new_node == NULL)
    {
        printf("malloc error !\n");
        exit(1);
    }


    new_node->next = NULL;
    return(new_node);
}


//表头初始化

void init_head(Node **head)
{
    (*head) = creat_node();
}

//打印链表信息
void list_print(Node **head)
{
    Node *temp = (*head)->next;
    while(temp != NULL)
    {
        printf("%d\n",temp->num);
        temp = temp->next;
    }
}

//头插法
void head_insret(Node **head,Node **new)
{


    (*new)->next = (*head)->next;
    (*head)->next = (*new);


}

尾插法
void tail_insret(Node **head,Node **new)
{
    Node *temp = (*head);


    while(temp->next != NULL)
    {
        temp = temp->next;
    }


    temp->next = (*new);
}


//对链表排序

void list_sort(Node **head)
{
    Node *ptr;
    Node *plast;//上一个节点
    Node *pnext;//下一个节点
    Node *temp = creat_node(); //新链表的临时表头
 
    while((*head)->next != NULL) //依次取旧表表头下一个节点(该节点存在)
    {
        plast = temp;
        pnext = temp->next;       
        ptr = (*head)->next->next;


        while(pnext != NULL && (*head)->next->num >= pnext->num)//在新表中找到插入点
        {
            plast = pnext;
            pnext = pnext->next;
        }
    
        plast->next = (*head)->next;
        (*head)->next->next = pnext;
        (*head)->next = ptr;
        
        if((*head)->next == NULL)
        {
            (*head) = temp;//旧表头指向新表头
            break;
        }
    }


    free(temp);
}


int main(int argc, char **argv)
{
    Node *head;
    Node *new;
    init_head(&head);
    srand((unsigned int)time(0));


    int i ;
    for(i = 1; i <= 100; i++)
    {
        new = creat_node();
        new->num = rand() % 100;
        head_insret(&head,&new);
    }


    list_print(&head);
    printf("\n");
    list_sort(&head);
    list_print(&head);
    return(0);

}



如果可以,尽量在建立链表的时候每个节点就按照顺序插入链表中。这样就可以免去后面排序的工作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值