LeetCode148:Sort List
题目:
Sort a linked list in O(n log n) time using constant space complexity.
解题思路:
根据题目要求,可知只能用归并排序,其他排序算法要么时间复杂度不满足,要么空间复杂度不满足
实现代码:
#include <iostream> using namespace std; /* 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) {} * }; */ struct ListNode { int val; ListNode *next; ListNode(int x):val(x), next(NULL) { } }; void addNode(ListNode* &head, int val) { ListNode *newNode = new ListNode(val); if(head == NULL) { head = newNode; } else { newNode->next = head; head = newNode; } } void PrintList(ListNode *root) { ListNode *head = root; while(head != NULL) { cout<<head->val<<"\t"; head = head->next; } cout<<endl; } class Solution { public: ListNode *sortList(ListNode *head) { if(head == NULL || head->next == NULL) return head; ListNode *quick = head; ListNode *slow = head; while(quick->next && quick->next->next)//通过两个指针,一个走两步、一个走一步,获得链表的中间节点 { slow = slow->next; quick = quick->next->next; } quick = slow; slow = slow->next; quick->next = NULL;//将链表的前半段进行截断 ListNode *head1 = sortList(head); ListNode *head2 = sortList(slow); return merge(head1, head2); } //归并两个有序链表 ListNode *merge(ListNode *head1, ListNode *head2) { if(head1 == NULL) return head2; if(head2 == NULL) return head1; ListNode *newHead = NULL; if(head1->val < head2->val) { newHead = head1; head1 = head1->next; } else { newHead = head2; head2 = head2->next; } ListNode *p = newHead; while(head1 && head2) { if(head1->val < head2->val) { p->next = head1; head1 = head1->next; } else { p->next = head2; head2 = head2->next; } p = p->next; } if(head1) p->next = head1; if(head2) p->next = head2; return newHead; } }; int main(void) { ListNode *head = new ListNode(5); addNode(head, 3); addNode(head, 10); addNode(head, 15); PrintList(head); Solution solution; head = solution.sortList(head); PrintList(head); return 0; }
-----------------------我和我追猪的梦-----------------------------------------------------------------
作者:mickole