sort list leetcode (归并排序)
来源:互联网 发布:舆情分析研判数据 编辑:程序博客网 时间:2024/05/19 01:07
#include<iostream>
#include<stdio.h>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* sortList(ListNode* head) {
return mergesort2(head);
}
ListNode* mergesort2(ListNode* head)
{
if(head==NULL||head->next==NULL) return head;
ListNode *fast=head,*slow=head;
while(fast->next!=NULL&&fast->next->next!=NULL)
{
fast=fast->next->next;
slow=slow->next; //找到中间点,slow
}
fast=slow; //fast 指向队尾
slow=slow->next;
fast->next=NULL;
ListNode* l1=mergesort2(head);
ListNode* l2=mergesort2(slow);
mergeTwoLists(l1,l2);
}
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2)
{
ListNode *helper=new ListNode(0);
ListNode *head=helper;
while(l1 && l2)
{
if(l1->val<l2->val) helper->next=l1,l1=l1->next;
else helper->next=l2,l2=l2->next;
helper=helper->next;
}
if(l1) helper->next=l1;
if(l2) helper->next=l2;
return head->next;
}
};
int main() {
Solution solution;
//int A[] = {2,4,7,9};
//int B[] = {5,6,4};
int i;
ListNode *head = NULL;
ListNode *head1 = (ListNode*)malloc(sizeof(ListNode));
ListNode *head2 = (ListNode*)malloc(sizeof(ListNode));
head1->next = NULL;
head2->next = NULL;
ListNode *node;
ListNode *pre = head1;
for(int i = 5;i >0;i--){
node = new ListNode(i);
// node->exp = A[i];
node->next = NULL;
pre->next = node;
pre = node;
}
/* pre = head2;
for(int i = 2;i < 5;i++){
node = new ListNode(i,i+1);
// node->val = B[i];
node->next = NULL;
pre->next = node;
pre = node;
}*/
head = solution.sortList(head1->next);
while(head != NULL){
// printf("%d %d ",head->coef,head->exp);
cout<<head->val<<' ';
head = head->next;
}
//i=(head1->val);
//cout<<i;
return 0;
}
0 0
- sort list leetcode (归并排序)
- Leetcode Sort List 链表归并排序
- Leetcode:Sort List 对单链表归并排序
- 【leetcode 单链表归并排序】Sort List
- 【LeetCode】 sort list 单链表的归并排序
- [leetcode] 134 Sort List (链表 & 归并排序)
- LeetCode Sort List(单链表归并排序)
- Leetcode: Sort List - 归并
- 归并排序---Sort List
- leetcode:Sort List(链表的归并排序)
- [C++]LeetCode: 125 Sort List (归并排序链表)
- LeetCode Sort List 链表的归并排序
- leetcode:Sort List 使用归并排序的解决思路
- LeetCode 148. Sort List 解题报告(归并排序小结)
- leetcode 148. Sort List 链表归并排序
- Sort List 归并排序链表
- 148. Sort List 链表归并排序
- Sort List —— 归并排序
- 四种方案解决ScrollView嵌套ListView问题
- scrapy爬虫-------命令解析
- struts详解
- windows 位图结构详解
- Python中函数的参数定义和可变参数
- sort list leetcode (归并排序)
- #leetcode#Maximum Subarray
- java Thread 简单总结
- iOS开发 -UIScrollView详解
- Java代码规范文档
- Openwrt启动后的脚本运行(二)
- HTML5之图形绘制技术(Canvas Vs SVG)
- Linux常用命令(六)——帮助命令
- jade学习总结