#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)
原文作者:小尼人00
原文地址: https://blog.csdn.net/robbyo/article/details/8651263
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
原文地址: https://blog.csdn.net/robbyo/article/details/8651263
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。