Leetcode[148]-Sort List
2015-06-10 13:23
387 查看
Sort a linked list in O(n log n) time using constant space complexity.
分析:题目要求时间复杂度为O(nlogn),所以一开始想到的就是快速排序,但是快速排序一直AC不了,然后就想到用归并排序,没想到归并排序竟然可以。下面给出详细代码:
归并排序需要做的
找到中间点
合并两个排好序的链表
递归实现归并排序
Code(c++):
分析:题目要求时间复杂度为O(nlogn),所以一开始想到的就是快速排序,但是快速排序一直AC不了,然后就想到用归并排序,没想到归并排序竟然可以。下面给出详细代码:
归并排序需要做的
找到中间点
合并两个排好序的链表
递归实现归并排序
Code(c++):
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: //mergeSort ListNode* sortList(ListNode* head) { if(head == NULL || head->next==NULL) return head; ListNode *mid = getMid(head); ListNode *left = head,*right; if(mid){ cout<<mid->val<<endl; right = mid->next; mid->next = NULL; } return mergeLinkedList(sortList(left),sortList(right)); } //get middle point from ListNode ListNode* getMid(ListNode* head){ if(head==NULL || head->next==NULL ) return head; ListNode* first = head,* second = head->next; while(second && second->next){ first = first->next; second = second->next->next; } return first; } //merge two sorted Linked List ListNode* mergeLinkedList(ListNode* first,ListNode* second){ if(first==NULL) return second; if(second==NULL) return first; ListNode* tail,* front; front = new ListNode(-1); tail = front; while(first && second){ if(first->val < second->val){ tail->next = first; first = first->next; tail = tail->next; }else{ tail->next = second; second = second->next; tail = tail->next; } } if(first){ tail->next =first; } if(second){ tail->next = second; } front = front->next; return front; } };
相关文章推荐
- erlang lists模块函数使用大全
- 老码农教你学英语
- 多个tomcat没有apache管理会导致session丢失
- normalize
- 第十四周项目一: 小玩文件
- 股市日记之十四:牛二阶段(上篇)
- android:layout_weight的真实含义
- 股市日记之十三:牛回头
- 生产者消费者模式实现
- 数据库链接字符串大集合
- shp文件及附属
- 【iOS开发-图层】创建图层,位置,锚点
- (正则表达式)注意事项
- 西岭 技术成长路线图
- 生产者消费者模式实现
- file not found app文件
- 工厂模式
- 26 Remove Duplicates from Sorted Array
- C primer plus(第五版)编程练习第十三章
- Svn客户端