【面试准备】letcode—sort list
来源:互联网 发布:wps数据透视表怎么拖动 编辑:程序博客网 时间:2024/05/21 21:42
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* merged_list(ListNode* l_head,ListNode* r_head){ListNode* merged_head = NULL;ListNode* merged_tail = NULL;if(l_head == NULL){return r_head;}if(r_head == NULL){return l_head;}while(l_head != NULL && r_head != NULL){if(l_head->val <= r_head->val){if(merged_head == NULL){merged_head = l_head;merged_tail = l_head;}else{merged_tail->next = l_head;merged_tail = merged_tail->next;}l_head = l_head->next;}else{if(merged_head == NULL){merged_head = r_head;merged_tail = r_head;}else{merged_tail->next = r_head;merged_tail = merged_tail->next;}r_head = r_head->next;}}if(l_head != NULL){merged_tail->next = l_head;}else if(r_head != NULL){merged_tail->next = r_head;}return merged_head;}ListNode* sortList(ListNode* head){if(head == NULL || head->next == NULL){return head;}ListNode* node = head ;ListNode* slow = head ;ListNode* fast = head ; while(fast->next != NULL && fast->next->next != NULL){slow = slow->next;fast = fast->next->next;}fast = slow->next;slow->next = NULL;slow = head;node = merged_list(sortList(slow),sortList(fast));return node;}};
0 0
- 【面试准备】letcode—sort list
- 【面试准备】letcode-Insertion Sort List
- 【面试准备】letcode-Reorder List
- 【面试准备】letcode—LRU
- 【面试准备】letcode-Linked List Cycle ||
- 【面试准备】letcode-Linked List Cycle |
- 【面试准备】letcode-Copy List with Random Pointer
- 【面试准备】letcode-Tow Sum
- 【面试准备】letcode-Word Break
- 【面试准备】letcode-Single Number
- 【面试准备】letcode—Max Points on a Line
- 【面试准备】letcode-Evaluate Reverse Polish Notation
- 【面试准备】letcode-Binary Tree Postorder Traversal
- 【面试准备】letcode-Binary Tree Preorder Traversal
- 【面试准备】list
- 面试准备—任重而道远
- 面试准备—数据结构
- LeetCode—Sort List
- Android技术积累:图片缓存管理
- Yii CGridView 基本使用(二)CCheckBoxColumn ButtonColumn afterAjaxUpdate
- hdu2087 剪花布条
- HDOJ 题目2639Bone Collector II(01背包第k优解)
- hdu 1005
- 【面试准备】letcode—sort list
- Openstack学习笔记之——Neutron网络理解
- 导航
- Java中的反射总结和实例全
- http错误代码
- Android RSA公钥加密
- GetMemory错误讲解(指针练习)
- iOS多线程
- 道奇经理大赞科比关键能力:希望队内球星学习他