[面试] 链表的归并排序 (非常好的题目 tx)
2013-03-08 16:18
316 查看
#include <iostream> #include <string> #include <cstring> #include <cstdlib> #include <cstdio> #include <cmath> #include <vector> #include <stack> #include <deque> #include <queue> #include <bitset> #include <list> #include <map> #include <set> #include <iterator> #include <algorithm> #include <functional> #include <utility> #include <sstream> #include <climits> #include <cassert> #define BUG puts("here!!!"); using namespace std; struct Node { int value; Node *next; }; /* 对两个有序链表进行归并 */ Node* mergeList(Node* head1, Node* head2) { Node* tmp; if(head1 == NULL) return head2; if(head2 == NULL) return head1; if(head1->value < head2->value) { tmp = head1; head1 = head1->next; } else { tmp = head2; head2 = head2->next; } tmp->next = mergeList(head1, head2); return tmp; } /* 归并排序 */ Node* mergeSort(Node* head) { if(head == NULL) return NULL; Node* r_head = head; Node* head1 = head; Node* head2 = head; while(head2->next != NULL && head2->next->next != NULL) { head1 = head1->next; head2 = head2->next->next; } if(head1->next == NULL) { // 说明只有一个节点,则返回该节点 return r_head; } head2 = head1->next; head1->next = NULL; head1 = head; r_head = mergeList(mergeSort(head1), mergeSort(head2)); return r_head; } int main() { return 0; }
相关文章推荐
- [面试] 链表的归并排序 (非常好的题目 tx)
- C语言单链表——之常见面试题目2
- 面试中常问的关于链表的题目
- 轻松搞定面试中的链表题目
- 轻松搞定面试中的链表题目
- 程序员面试题目总结--链表(2)【找出单链表中的倒数第K个元素】
- 轻松搞定面试中的链表题目
- 轻松搞定面试中的链表题目
- 【剑指Offer面试编程题】题目1517:链表中倒数第k个结点--九度OJ
- 【剑指Offer面试编程题】题目1503:二叉搜索树与双向链表--九度OJ
- 轻松搞定面试中的链表题目
- 面试题目-链表反转
- 轻松搞定面试中的链表题目
- 链表面试笔试题目总结
- 【剑指Offer面试编程题】题目1517:链表中倒数第k个结点--九度OJ
- 面试中常问的关于链表的题目
- 链表翻转(面试题目 C语言实现)
- 轻松搞定面试中的链表题目
- 面试题目 链表专题
- 轻松搞定面试中的链表题目