• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ying_vincent
博客园    首页    新随笔    联系   管理    订阅  订阅

Data Structure Linked List: Merge Sort for Linked Lists

http://www.geeksforgeeks.org/merge-sort-for-linked-list/

 1 #include <iostream>
 2 #include <vector>
 3 #include <algorithm>
 4 #include <queue>
 5 #include <stack>
 6 #include <string>
 7 #include <fstream>
 8 #include <map>
 9 #include <set>
10 using namespace std;
11 
12 struct node {
13     int data;
14     node *next;
15     node() : data(0), next(NULL) { }
16     node(int d) : data(d), next(NULL) { }
17 };
18 
19 void push(node* &head, int k) {
20     node *new_node = new node(k);
21     new_node->next = head;
22     head = new_node;
23 }
24 
25 void print(node* head) {
26     if (!head) return;
27     cout << head->data << " ";
28     print(head->next);
29 }
30 
31 void frontbacksplit(node *head, node *&a, node *&b) {
32     node *p, *q;
33     if (!head || !head->next) {
34         a = head;
35         b = NULL;
36         return;
37     }
38     p = head;
39     q = head->next;
40     while (q) {
41         q = q->next;
42         if (q) {
43             q = q->next;
44             p = p->next;
45         }
46     }
47     a = head;
48     b = p->next;
49     p->next = NULL;
50 }
51 
52 node *sortmerge(node *a, node *b) {
53     node *ans = NULL;
54     if (!a) return b;
55     if (!b) return a;
56     if (a->data < b->data) {
57         ans = a;
58         ans->next = sortmerge(a->next, b);
59     }
60     else {
61         ans = b;
62         ans->next = sortmerge(a, b->next);
63     }
64     return ans;
65 }
66 
67 void mergesort(node *&head) {
68     if (!head || !head->next) return;
69     node *a, *b;
70     node *h = head;
71     frontbacksplit(h, a, b);
72     mergesort(a);
73     mergesort(b);
74     head = sortmerge(a, b);
75 }
76 
77 int main() {
78     node *head = NULL;
79     push(head, 15);
80     push(head, 10);
81     push(head, 5);
82     push(head, 20);
83     push(head, 3);
84     push(head, 2);
85     mergesort(head);
86     print(head);
87     return 0;
88 }

 

posted @ 2014-04-10 12:48  ying_vincent  阅读(340)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3