您的位置:首页 > 其它

148. Sort List

2018-03-06 08:17 204 查看
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;

int length = 0;
ListNode * cur = head;

while(cur)
{
length ++ ;
cur = cur->next;
}

ListNode dump(0);
dump.next = head;
ListNode *left = NULL;
ListNode *right = NULL;
ListNode *tail = NULL;

for( int step=1; step<length; step<<=1 )
{
cur = dump.next;
tail = &dump;
while(cur)
{
left = cur;
right = split(left, step);
cur = split(right, step);
tail = Merge(left, right, tail);
}
}
return dump.next;
}

ListNode * split(ListNode *head, int step)
{
for(int i=1; head && i<step; i++) head = head->next;
if ( !head ) return NULL;
ListNode *second = head->next;
head->next = NULL;
return second;
}

ListNode * Merge(ListNode * left, ListNode * right, ListNode * tail )
{
ListNode * cur = tail;
while (left && right)
{
if ( left->val < right->val )
{
cur->next = left;
cur = left;
left = left->next;

}else
{
cur->next = right;
cur = right;
right = right->next;
}
}

cur->next = ( left ? left : right );
while (cur->next) { cur = cur->next ;}
return cur;
}
};递归方法:class Solution {
public:
ListNode* merge( ListNode* head1 , ListNode * head2){
ListNode* d = new ListNode (0); // dummy node
ListNode* e = d;
while(head1||head2){
if(head1 && (!head2 || head1->val <= head2 -> val) ){
e=e->next= head1 ;
head1 = head1 -> next;
}
if(head2 && (!head1 || head2->val < head1 -> val) ){
e=e->next= head2 ;
head2 = head2 -> next;
}
}
e->next = NULL;
return d->next;
}
ListNode* sortLis
4000
t(ListNode* head) {
if(!head || !head->next) return head;
ListNode* slow = head;
ListNode* fast =head->next;
while(fast && fast->next){ // to find middle node
fast= fast->next->next;
slow = slow->next;
}
ListNode* headb = slow->next; // headb is start of 2nd half of list
slow->next = NULL;
return merge(sortList(head) , sortList(headb));
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: