• [面试] 链表的归并排序 (非常好的题目 tx)


    #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;
    }
    

  • 相关阅读:
    CODEFORCES 429B 动态规划
    HDU 2084(DP)
    最大公约数算法(待续)
    spring---aop 配置
    代理模式
    spring--学习之IOC DI
    spring--基本介绍
    JAVASE 面试总结(1)
    工厂模式
    建造者模式
  • 原文地址:https://www.cnblogs.com/robbychan/p/3787015.html
Copyright © 2020-2023  润新知