leetcode Sort List

来源:互联网 发布:轮回转世是真的吗 知乎 编辑:程序博客网 时间:2024/06/10 00:59
/** * 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){            return head;        }        if(head->next == NULL){            return head;        }        if(head->next->next == NULL){            if(head->next->val < head->val){                ListNode *tmp = head->next;                head->next->next = head;                head->next = NULL;                return tmp;            }            else{                return head;            }        }        ListNode* fast, *slow;        fast = slow = head;        while(fast->next){            fast = fast->next->next;            slow = slow->next;            if(fast == NULL){                break;            }        }        ListNode* rec = slow, *recnext = slow->next;        ListNode *first, *second;        slow->next = NULL;        first = sortList(head);        second = sortList(recnext);        ListNode *newhead = new ListNode(0);        ListNode *newtmp = newhead;        while(first != NULL && second != NULL){            if(first->val <= second->val){                newtmp->val = first->val;                   first = first->next;            }            else{                newtmp->val = second->val;                second = second->next;            }            newtmp->next = new ListNode(0);            newtmp = newtmp->next;        }        if(first != NULL){            newtmp->val = first->val;            newtmp->next = first->next;        }        else{            newtmp->val = second->val;            newtmp->next = second->next;        }        return newhead;    }};
0 0