lintcode:Sort List
来源:互联网 发布:网络主播盈利模式 编辑:程序博客网 时间:2024/05/15 01:55
Sort a linked list in O(n log n) time using constant space complexity.
Example
Given 1-3->2->null, sort it to 1->2->3->null.
/** * Definition of ListNode * class ListNode { * public: * int val; * ListNode *next; * ListNode(int val) { * this->val = val; * this->next = NULL; * } * } */class Solution {public: /** * @param head: The first node of linked list. * @return: You should return the head of the sorted linked list, using constant space complexity. */ ListNode *getMidNode(ListNode *head) { if (!head) return NULL; ListNode *pSlowNode = head; ListNode *pFastNode = head; while (pFastNode->next && pFastNode->next->next) { pFastNode = pFastNode->next->next; pSlowNode = pSlowNode->next; } return pSlowNode; } ListNode *mergeNode(ListNode *head1, ListNode *head2) { if (!head1 && !head2) return NULL; else if (head1 == NULL) return head2; else if (head2 == NULL) return head1; ListNode fakeHead(-1); ListNode *pCurNode = &fakeHead; ListNode *p1 = head1; ListNode *p2 = head2; while (p1 && p2) { if (p1->val <= p2->val) { pCurNode->next = p1; p1 = p1->next; } else { pCurNode->next = p2; p2 = p2->next; } pCurNode = pCurNode->next; } if (p1) pCurNode->next = p1; if (p2) pCurNode->next = p2; return fakeHead.next; } ListNode *sortList(ListNode *head) { // write your code here if (!head) return NULL; if (head->next == NULL) return head; ListNode *midNode = getMidNode(head); ListNode *p1 = head; ListNode *p2 = midNode->next; midNode->next = NULL; ListNode *n1 = sortList(p1); ListNode *n2 = sortList(p2); return mergeNode(n1, n2); }};
0 0
- lintcode:Sort List
- [LintCode]Insertion Sort List
- LintCode:M-Sort List
- 【LintCode】Sort List(笔记)
- [Lintcode]Sort List链表排序
- 【lintcode】——链表插入排序-Insertion Sort List
- Lintcode - sort colors II
- LintCode Wiggle Sort II
- Lintcode:wiggle-sort
- lintcode:Sort Colors
- lintcode:Sort Colors II
- LintCode-463.Sort Integers
- [LintCode]Sort Colors II
- [LintCode]Wiggle Sort
- [LintCode]Sort Integers(C++)
- list sort
- list sort
- Sort List
- 请一个在字符串中找出连续最长的数字串,并把这个串的长度返回;如果存在长度相同的连续数字串,返回最后一个连续数字串
- POJ 3104 Drying (二分搜索)
- Android: AudioFlinger中AudioPolicy的简单介绍
- 算法竞赛入门经典读书笔记(三)7.2枚举排列
- 【iOS开发问题】添加UIImageView不显示的问题
- lintcode:Sort List
- java.lang.IllegalArgumentException: Empty bindArgs
- 如何给Ubuntu 安装Vmware Tools
- 第9周项目4我的向量类
- Thrift RPC 使用指南实战(附golang&PHP代码)
- 算法-八皇后问题
- 两个想法和痛点:登山导航?上门试鞋?
- 算法竞赛入门经典读书笔记(四)7.3子集生成
- 机试练习HW