Sort List

来源:互联网 发布:linux环境安装jmeter 编辑:程序博客网 时间:2024/05/17 18:48

Sort List 

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

题目来自leetcode:https://leetcode.com/problems/sort-list/

解:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:        ListNode * merge(ListNode * l1, ListNode * l2)    {        ListNode * ret;        if(l1->val<l2->val)        {            ret=l1;            l1=l1->next;        }        else        {            ret=l2;            l2=l2->next;        }        ListNode * tail=ret;                while(l1 && l2)        {            if(l1->val<l2->val)            {                tail->next=l1;                tail=l1;//开始忘记了这一句,低级失误                l1=l1->next;            }            else            {                tail->next=l2;                tail=l2;                l2=l2->next;            }        }        tail->next= l1 ? l1 : l2;        return ret;    }        ListNode* sortList(ListNode* head) {//本题思想:归并排序,通过快慢指针实现中间节点的查询,将链表分成两个子链表        if(head==NULL || head->next==NULL)            return head;                ListNode * slow=head;        ListNode * quik=head;        while(quik->next && quik->next->next)        {            slow=slow->next;            quik=quik->next->next;        }        quik=slow->next;//包含只有两个元素的情况        slow->next=NULL;                ListNode * l1=sortList(head);        ListNode * l2=sortList(quik);        ListNode * ret=merge(l1, l2);                return ret;    }};



0 0
原创粉丝点击