LeetCode刷题(C++)——Sort List(Medium)

来源:互联网 发布:mac锁定触控板快捷键 编辑:程序博客网 时间:2024/06/01 16:36

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

/** * 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) {        if(head==NULL || head->next==NULL){            return head;        }        ListNode* a=head, *b=head;        while(b->next && b->next->next){            a=a->next;            b=b->next->next;        }        b=sortList(a->next);        a->next=NULL;        a=sortList(head);        ListNode* tail=NULL;        while(a && b){            if(a->val < b->val){                if(tail){                    tail=tail->next=a;                }                else{                    head=tail=a;                }                a=a->next;            }            else{                if(tail){                    tail=tail->next=b;                }                else{                    head=tail=b;                }                b=b->next;            }        }        if(a){            if(tail){                tail->next=a;            }            else{                head=tail;            }        }        else{            if(tail){                tail->next=b;            }            else{                head=b;            }        }        return head;    }};


阅读全文
1 0
原创粉丝点击