Sort List (使用归并排序的链表排序)
2014-11-18 13:18
441 查看
Sort a linked list in O(n log n) time using constant space complexity.
C++代码的实现:
运行结果:
参考:http://www.tuicool.com/articles/2eemi2
http://www.cnblogs.com/tenosdoit/p/3666585.html
C++代码的实现:
#include<iostream> #include<new> using namespace std; //Definition for singly-linked list. struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode *sortList(ListNode *head) { if(head==NULL) return NULL; //递归的结束条件,注意,与对数组的归并排序不同 if(head->next==NULL) return head; ListNode *p=head; //q不能从head开始,为什么呢? ListNode *q=head->next; ListNode *l2=NULL; while(q&&q->next) { p=p->next; q=q->next->next; } l2=p->next; p->next=NULL; return Merge(sortList(head),sortList(l2)); } ListNode *Merge(ListNode *l1,ListNode *l2) { ListNode *pre=l1; ListNode *p=l1; ListNode *q=l2; while(p&&q) { if(p->val<=q->val) { pre=p; p=p->next; continue; } else { l2=q->next; q->next=NULL; q->next=p; if(p==l1) l1=q; else pre->next=q; pre=q; q=l2; } } if(q) pre->next=q; return l1; } void createList(ListNode *&head) { ListNode *p=NULL; int i=0; int arr[10]= {5,7,6,4,8,3,9,3,10,1}; for(i=0; i<10; i++) { if(head==NULL) { head=new ListNode(arr[i]); if(head==NULL) return; } else { p=new ListNode(arr[i]); p->next=head; head=p; } } } }; int main() { Solution s; ListNode *L=NULL; s.createList(L); ListNode *L1=NULL; L1=s.sortList(L); while(L1) { cout<<L1->val<<" "; L1=L1->next; } }
运行结果:
参考:http://www.tuicool.com/articles/2eemi2
http://www.cnblogs.com/tenosdoit/p/3666585.html
相关文章推荐
- Insertion Sort List 使用插入排序将链表排序
- 使用Collections.sort()对List/ArrayList进行排序 推荐
- Sort List 链表排序@LeetCode
- 排序链表(Sort linked list)
- LeetCode OJ 之 Insertion Sort List (插入法排序链表)
- leetcode:Sort List(链表的归并排序)
- 使用c++的 list.sort()进行排序
- Insertion Sort List 链表插入排序
- 使用Collections.sort方法对list排序的两种方法
- 单链表排序(sort list)
- LeetCode OJ 之 Sort List (排序链表)
- 不使用遍历循环、Linq与Lamba表达式快速对List集合进行筛选与排序——在集合类里使用Find、FindAll与Sort
- 单链表的排序 快速排序 归并排序 quicksort mergesort
- LeetCode Sort List(链表排序)
- LeetCode-Sort List-链表排序-归并排序+链表调整
- list排序;arrays.sort使用
- 使用Collections.sort()方法扩展list集合中的数据并对其进行排序
- Leetcode Sort List 链表归并排序
- Insertion Sort List ——链表插入排序
- LeetCode-Insertion Sort List-链表插入排序-链表操作