list
来源:互联网 发布:巨杉数据库 olap 编辑:程序博客网 时间:2024/06/06 10:20
一,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* getMiddleNodeOfList(ListNode* head){ ListNode* slow = head; ListNode* fast = head; if(head == NULL){ return NULL; } while(fast->next != NULL && fast->next->next != NULL) { slow = slow->next; fast = fast->next->next; } return slow; } ListNode* sortList(ListNode* head) { if(head == NULL || head->next == NULL) { return head; } ListNode *middle = getMiddleNodeOfList(head); ListNode *next = middle->next; middle->next = NULL; return mergeList(sortList(head), sortList(next)); } ListNode* mergeList(ListNode *list1, ListNode *list2){ ListNode *head = new ListNode(-1); ListNode *p1, *p2, *pre = head; p1 = list1; p2 = list2; head->next = NULL; while(p1 != NULL && p2 != NULL){ if(p1->val < p2->val){ pre->next = p1; pre = p1; p1 = p1->next; } else { pre->next = p2; pre = p2; p2 = p2->next; } } if(p1 != NULL){ pre->next = p1; } if(p2 != NULL){ pre->next = p2; } return head->next; }};
阅读全文
0 0
- List
- list
- List
- LIST
- list
- list
- List
- list
- list
- List
- list
- LIST
- List
- List
- List
- list
- list
- list
- docker容器里安装ssh
- Java Switch 和 If else 使用效率对比和分析
- 数据库大并发操作要考虑死锁和锁的性能问题
- FLASH 驱动程序设计 --- 块设备驱动设计
- spark streaming 整合kafka
- list
- Python的学习(二)----单引号、双引号和三双引号的区别
- python使用opencv驱动摄像头获取视频并保存
- 解决 javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException
- 读人生元编程的杂七杂八
- 隐式意图 implicit intent
- Android 解决fragment replace方法低效的问题
- 优达学城《Version control with Git》笔记
- 地域二级选择