//#148 Sort List
//60ms 96.38%
#include <iostream>
using namespace std;
class Solution
{
public:
ListNode* sortList(ListNode* head)
//decided to use "marge sort", recurrence as the way to solve this problem
{
if(head == NULL) return head;
if(head->next == NULL) return head;
//merge(left_par, right_par);
ListNode *fast, *slow;
fast = head;
slow = head;
while(fast->next != NULL && fast->next->next != NULL)
{
fast = fast->next->next;
slow = slow->next;
}
fast = slow->next;
slow->next = NULL;
slow = head;
return merge(sortList(fast), sortList(slow));
//step 1. using fast-slow pointers to find the middle point of this sortlist
//and to define two parts
//setp 2. using sortlist recursively
//step 3. merge
}
ListNode* merge(ListNode* first, ListNode* second)
{
ListNode *new_head(NULL), *p(NULL);
if(first->val < second->val)
{
new_head = first;
first = first->next;
}
else
{
new_head = second;
second = second->next;
}
p = new_head;
p->next = NULL;
while(first != NULL && second != NULL)
{
if(first->val < second->val)
{
p->next = first;
first = first->next;
}
else
{
p->next = second;
second = second->next;
}
p = p->next;
p->next = NULL;
}
if(first != NULL)
{
p->next = first;
}
else
{
p->next = second;
}
return new_head;
}
};
[Leetcode]#148 Sort List
最新推荐文章于 2024-09-11 22:27:08 发布