[LeetCode] Sort List

Sort List

Sort a linked list in O(n log n) time using constant space complexity.

解题思路:

题意为以常量存储空间和O(nlogn)时间复杂度来排序链表。

可以用合并排序法,并用双指针法来找到中间节点。

产生一个头结点方便编码。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* sortList(ListNode* head) {
        ListNode* myHead = new ListNode(0);
        myHead->next = head;
        myHead = mergeSort(myHead);
        head = myHead->next;
        delete myHead;
        return head;
    }
    
    ListNode* mergeSort(ListNode* head){
        if(head->next==NULL || head->next->next==NULL){
            return head;
        }
        ListNode* one = head, *two = head;
        while(two->next!=NULL && two->next->next!=NULL){
            one = one->next;
            two = two->next->next;
        }
        two = new ListNode(0);
        two->next = one->next;
        one->next = NULL;
        
        one = mergeSort(head);
        two = mergeSort(two);
        one = merge(one, two);
        return one;
    }
    
    ListNode* merge(ListNode* head1, ListNode* head2){
        ListNode* head = new ListNode(0);
        ListNode* tail = head;
        while(head1->next!=NULL && head2->next!=NULL){
            if(head1->next->val > head2->next->val){
                tail->next = head2->next;
                head2->next = head2->next->next;
            }else{
                tail->next = head1->next;
                head1->next = head1->next->next;
            }
            tail = tail->next;
        }
        if(head1->next!=NULL){
            tail->next = head1->next;
        }
        if(head2->next!=NULL){
            tail->next = head2->next;
        }
        delete head1;
        delete head2;
        return head;
    }
};

展开阅读全文
©️2020 CSDN 皮肤主题: 书香水墨 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值