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

  • 相关阅读:
    Eclipse OSBP 设置 配置
    限制文本框输入的内容
    jquery 操作iframe的几种方法总结
    利用PLUPLOAD上传大文件
    oracle contains
    JSON.parse
    js正则表达式replace里有变量的解决方法用到RegExp类
    Web API WinForm使用HttpClient呼叫Web API
    JQUERY DIALOG窗格内不能使用FORM
    Access forbidden! XAMPP虚拟主机的问题
  • 原文地址:https://www.cnblogs.com/robbychan/p/3787015.html
Copyright © 2011-2022 走看看