zoukankan      html  css  js  c++  java
  • [面试] 链表的归并排序 (非常好的题目 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;
    }
    

  • 相关阅读:
    mysql-四舍五入
    数据库基础
    大白话五种IO模型
    Python程序中的协程操作-gevent模块
    Python程序中的协程操作-greenlet模块
    协程基础
    Python程序中的线程操作-concurrent模块
    Python程序中的线程操作-线程队列
    Python程序中的线程操作-锁
    Python程序中的线程操作-守护线程
  • 原文地址:https://www.cnblogs.com/robbychan/p/3787015.html
Copyright © 2011-2022 走看看