Data Structure Linked List: Merge Sort for Linked Lists
2014-04-10 12:48
344 查看
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(0), 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, 15); push(head, 10); push(head, 5); push(head, 20); push(head, 3); push(head, 2); mergesort(head); print(head); return 0; }
相关文章推荐
- Data Structure Linked List: Write a function to get the intersection point of two Linked Lists.
- [LeetCode] merge sort for linked list
- LeetCode_Linked List_Merge Two Sorted Lists
- Data Structure Linked List: Write a function to reverse a linked list
- LeetCode[Linked List]: Merge k Sorted Lists
- Data Structure Linked List: Function to check if a singly linked list is palindrome
- Data Structure Linked List: Flattening a Linked List
- Data Structure Linked List: Reverse a Linked List in groups of given size
- LeetCode 学习 LinkedList 专项(4)—— Merge Two Sorted Lists
- Data Structure Binary Tree: Convert a given Binary Tree to Doubly Linked List
- Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
- LinkedList-21-Merge Two Sorted Lists
- (java) Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
- Insertion Sort List && Remove Duplicates from Sorted List II && Intersection of Two Linked Lists
- Data Structure Study: Linked List(Part A)
- 链表的归并排序 特殊优化, merge sort for list,非快慢指针法
- Build Tree View Structure for SharePoint List Data
- 【DataStructure&AlgorithmInJava】Ch05-LinkedListDemo1
- [LinkedIn]linked List data structure so that add/insert, remove, get random in O(1) constant time
- LeetCode 21 Merge Two Sorted Lists(合并两个已排序的链表)(Linked List)