LeetCode题解——Sort List
来源:互联网 发布:郑州网络电话软件 编辑:程序博客网 时间:2024/05/22 00:48
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) {} * }; */ /** TLEclass Solution {public: ListNode* sortList(ListNode* head) { ListNode* list = head; while(head!=NULL){ ListNode* p = head; while(p->next!=NULL){ if(p->val > p->next->val) { int t = p->val; p->val = p->next->val; p->next->val = t; } p = p->next; } head = head->next; } return list; }};*/class Solution {public: ListNode* sortList(ListNode* head) { if(head == NULL || head->next == NULL) return head; ListNode* l1= head; ListNode* l2= head->next; while(l2!=NULL && l2->next!=NULL) { l1 = l1->next; l2 = l2->next->next; } l2 = l1->next; l1->next = NULL; return mergeTwoLists(sortList(head),sortList(l2)); } ListNode* mergeTwoLists(ListNode *l1, ListNode *l2) { if(l1 == NULL) return l2; if(l2 == NULL) return l1; if(l1->val < l2->val) { l1->next = mergeTwoLists(l1->next, l2); return l1; } else { l2->next = mergeTwoLists(l2->next, l1); return l2; } }};
0 0
- LeetCode题解——Sort List
- LeetCode题解:Sort List
- LeetCode题解:Insertion Sort List
- LeetCode—Sort List
- LeetCode——Sort List
- LeetCode —— Sort List
- LeetCode——Sort List
- LeetCode—Insertion Sort List
- LeetCode Insertion Sort List 最新题解
- LeetCode 题解(41): Insertion Sort List
- LeetCode 题解(140): Sort List
- leetcode题解Java | 148. Sort List
- LeetCode题解(Week2):148. Sort List
- leetcode题解-147. Insertion Sort List
- LeetCode——Insertion Sort List
- LeetCode——Insertion Sort List
- leetcode 147 —— Insertion Sort List
- leetcode 148 —— Sort List
- Mysql temporary table
- UVA 725 Division
- Qt发布Release版本注意事项
- 西天取经后续
- ios 判断字符串中是否包含中文
- LeetCode题解——Sort List
- 坑爹的BOM PHP
- THE DRUNK JAILER(POJ--1218
- 题目 H
- #import,#include,@class
- 红黑树
- Qt Creator管理多个项目
- Apache2.4+Tomcat7集群搭建
- 【node.js】windows安装express:'express' 不是内部或外部命令,也不是可运行的程序或批处理文件。