Leetcode_sort-list(c++ version)
来源:互联网 发布:上海银行mac控件下载 编辑:程序博客网 时间:2024/04/29 14:54
地址:http://oj.leetcode.com/problems/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 *sortList(ListNode *head) {if(!head || !head->next)return head;ListNode*p1 = head, *p2 = head, *ph = NULL;while(p1){p1 = p1->next;if(p1)p1 = p1->next;ph = p2;p2 = p2->next;}ph->next = NULL;head = sortList(head);p2 = sortList(p2);ListNode*pans = NULL;ListNode**ppcur = &pans;while(head && p2){if(head->val < p2->val){*ppcur = head;head = head->next;}else{*ppcur = p2;p2 = p2->next;}ppcur = &((*ppcur)->next);}if(head)*ppcur = head;else if(p2)*ppcur = p2;return pans;}};
下面的解法可能更好理解啊,先把链表切的短的不能再短(1个node或者0个),再把这些短的不能再短的链表缝起来。
class Solution {private:ListNode* merge(ListNode*l1, ListNode*l2) {if(!l1)return l2;else if(!l2)return l1;ListNode*head = NULL, *p1 = l1, *p2 = l2, *cur = NULL;while(p1 && p2) {if(p1->val <= p2->val) {if(!head)head = cur = p1;elsecur = cur->next = p1;p1 = p1->next;} else {if(!head)head = cur = p2;elsecur = cur->next = p2;p2 = p2->next;}}if(p1)cur->next = p1;elsecur->next = p2;return head;}void split(ListNode*head, ListNode**l1, ListNode**l2) {ListNode* lnode = *l1, *rnode = *l2;if(!head)lnode = rnode = NULL;else if(!head->next) {lnode = head;rnode = NULL;} else {lnode = rnode = head;ListNode *tmp = NULL;while(lnode) {lnode = lnode->next;if(lnode) {lnode = lnode->next;tmp = rnode;rnode = rnode->next;}}tmp->next = NULL;*l1 = lnode = head;*l2 = rnode;}}public:ListNode *sortList(ListNode *head) {if(!head || !head->next)return head;ListNode*l1 = NULL, *l2 = NULL;split(head, &l1, &l2);l1 = sortList(l1);l2 = sortList(l2);return merge(l1, l2);}};
0 0
- Leetcode_sort-list(c++ version)
- leetcode_Sort List
- LeetCode_Sort List
- leetcode_Sort List
- leetcode_Sort a linked list using insertion sort.
- LeetCode_Sort Colors
- leetcode_Sort a linked list in O(n log n) time using constant space complexity.
- string replace C version
- List-C
- C list
- SWEBOK Version 3 Consolidated Reference List
- bubble sort in linked list....(java version)
- Leetcode_linked-list-cycle(c++ and python version)
- Leetcode_sort-colors(c++ and python updated)
- Win32 API GetLocalTime C version
- Alarm Clock C/C++ Version
- 【c/c++】list
- Leetcode_remove-duplicates-from-sorted-list (updated c++ and python version)
- Activity的Intent Filter
- Android 操作系统 获取Root权限 原理解析
- Servlet事件监听器
- Get Bearer Token when login in
- 自定义进度条
- Leetcode_sort-list(c++ version)
- LeetCode: Search Insert Position [034]
- windows server 2003 程序不兼容的解决方法
- 暴力枚举
- Servlet事件监听器(二)
- PAT A 1052. Linked List Sorting (25)
- leetcode1:Reverse Words in a String
- DFS 我的模板 2 1
- IOS开发编码及命名规范