一,Sort List
题目描述
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* getMiddleNodeOfList(ListNode* head){
ListNode* slow = head;
ListNode* fast = head;
if(head == NULL){
return NULL;
}
while(fast->next != NULL && fast->next->next != NULL) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
ListNode* sortList(ListNode* head) {
if(head == NULL || head->next == NULL) {
return head;
}
ListNode *middle = getMiddleNodeOfList(head);
ListNode *next = middle->next;
middle->next = NULL;
return mergeList(sortList(head), sortList(next));
}
ListNode* mergeList(ListNode *list1, ListNode *list2){
ListNode *head = new ListNode(-1);
ListNode *p1, *p2, *pre = head;
p1 = list1;
p2 = list2;
head->next = NULL;
while(p1 != NULL && p2 != NULL){
if(p1->val < p2->val){
pre->next = p1;
pre = p1;
p1 = p1->next;
} else {
pre->next = p2;
pre = p2;
p2 = p2->next;
}
}
if(p1 != NULL){
pre->next = p1;
}
if(p2 != NULL){
pre->next = p2;
}
return head->next;
}
};