2020年11月21日

leetcode刷题记录 148.排序链表
思路
归并排序
代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* merge(struct ListNode* head1,struct ListNode* head2){
    //在头结点前面加入一个结点确保对头结点操作的一致性,并进行初始化
    struct ListNode* dummyhead=(struct ListNode*)malloc(sizeof(struct ListNode));
    dummyhead->val=0;
    struct ListNode* temp=dummyhead;
    while(head1!=NULL&&head2!=NULL){
        if(head1->val<=head2->val){
            temp->next=head1;
            head1=head1->next;
        }
        else{
            temp->next=head2;
            head2=head2->next;
        }
        temp=temp->next;
    }
    if(head1!=NULL){
        temp->next=head1;
    }
    else if(head2!=NULL){
        temp->next=head2;
    }
    return dummyhead->next;

}
struct ListNode* sortList(struct ListNode* head){
    //对特殊情况进行处理
    if(head==NULL||head->next==NULL) return head;
    //求链表的长度
    int length=0;
    struct ListNode* node=head;
    while(node){
        length++;
        node=node->next;
    }
    //在头结点前面加入一个结点确保对头结点操作的一致性
    struct ListNode* dummyhead=(struct ListNode*)malloc(sizeof(struct ListNode));
    dummyhead->next=head;
    //进行归并排序
    for(int sublength=1;sublength<length;sublength<<=1){//每进行一次新的循环,就是一轮新的归并排序
        struct ListNode *curr=dummyhead->next,*prev=dummyhead;
        while(curr){//在一轮归并排序中,对所有元素进行排序
            //找到需要排序的第一个子链表
            struct ListNode* head1=curr;
            for(int i=1;i<sublength&&curr->next!=NULL;i++) curr=curr->next;
            //找到需要排序的第二个子链表
            struct ListNode* head2=curr->next;
            curr->next=NULL;//让第一个子链表独立
            curr=head2;
            for(int i=1;i<sublength&&curr != NULL&&curr->next!=NULL;i++) curr=curr->next;
            struct ListNode *next=NULL;
            if(curr!=NULL){
                 next=curr->next;
                 curr->next=NULL;
            }
           struct ListNode *merged=merge(head1,head2);
           prev->next=merged;
           while(prev->next){
               prev=prev->next;
           }
           curr=next;
        }
    }
    return dummyhead->next;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值