Data Structure Linked List: Merge Sort for Linked Lists
2024-09-08 07:12:28
http://www.geeksforgeeks.org/merge-sort-for-linked-list/
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <stack>
#include <string>
#include <fstream>
#include <map>
#include <set>
using namespace std; struct node {
int data;
node *next;
node() : data(), next(NULL) { }
node(int d) : data(d), next(NULL) { }
}; void push(node* &head, int k) {
node *new_node = new node(k);
new_node->next = head;
head = new_node;
} void print(node* head) {
if (!head) return;
cout << head->data << " ";
print(head->next);
} void frontbacksplit(node *head, node *&a, node *&b) {
node *p, *q;
if (!head || !head->next) {
a = head;
b = NULL;
return;
}
p = head;
q = head->next;
while (q) {
q = q->next;
if (q) {
q = q->next;
p = p->next;
}
}
a = head;
b = p->next;
p->next = NULL;
} node *sortmerge(node *a, node *b) {
node *ans = NULL;
if (!a) return b;
if (!b) return a;
if (a->data < b->data) {
ans = a;
ans->next = sortmerge(a->next, b);
}
else {
ans = b;
ans->next = sortmerge(a, b->next);
}
return ans;
} void mergesort(node *&head) {
if (!head || !head->next) return;
node *a, *b;
node *h = head;
frontbacksplit(h, a, b);
mergesort(a);
mergesort(b);
head = sortmerge(a, b);
} int main() {
node *head = NULL;
push(head, );
push(head, );
push(head, );
push(head, );
push(head, );
push(head, );
mergesort(head);
print(head);
return ;
}
最新文章
- centos 6.5 升级内核 linux 3.12.17 (笔记 实测)
- Constraint4:default约束
- sizeof和strlen()区别
- uC/OS-II任务(OS_task)块
- Golang 安装及配置教程 for Mac
- [奇葩 bug]视图在 ipad5 上正常显示,在 iPad3上超出了边界
- 【转】VS2012编译出来的程序,在XP上运行,出现“.exe 不是有效的 win32 应用程序” “not a valid win32 application”
- 白书P60 - 硬币问题
- httpclient response 重定向
- Android:简单的弹幕效果达到
- J2EE判断重复的数据
- firefox 28.0
- Druid连接池配置(java无框架)
- 前端工程之CDN部署
- New UWP Community Toolkit - Staggered panel
- 如何成为java高手
- <;亲测>;CentOS7yum安装PHP7.2
- win7开始菜单路径
- C#复制数组的两种方式,以及效率比较
- 使用pidstat监控资源使用