首页 > 代码库 > LeetCode OJ-- Sort List **@
LeetCode OJ-- Sort List **@
链表排序,要求使用 O(nlgn) 时间,常量空间。
使用归并的思路
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *findMid(ListNode *head) { ListNode *mid; ListNode *fast = head->next; ListNode *slow = head; while(fast && fast->next) { fast = fast->next; fast = fast->next; slow = slow->next; } mid = slow; return mid; } ListNode *sortList(ListNode *head) { if(head == NULL || head->next == NULL) return head; ListNode *tmp = findMid(head); ListNode *right = sortList(tmp->next); tmp->next = NULL; ListNode *left = sortList(head); ListNode *newHead = new ListNode(-1); newHead->next = merge(left,right); return newHead->next; } ListNode *merge(ListNode *left, ListNode *right) { ListNode *dummy = new ListNode(-1); for(ListNode *p = dummy; left!=NULL || right!= NULL; p = p->next) { int leftVal = left == NULL? INT_MAX:left->val; int rightVal = right == NULL?INT_MAX:right->val; if(leftVal <= rightVal) { p->next = left; left = left->next; } else { p->next = right; right = right->next; } } return dummy->next; }};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。