c_cpp 递归合并

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 递归合并相关的知识,希望对你有一定的参考价值。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* sortList(ListNode* head) {
        ListNode *p1, *p2, *front, *back;
        p1 = head;
        p2 = head;
        
        if (head == NULL || head->next == NULL) return head;
        else {
            while (p1->next != NULL && p1->next->next != NULL) {
                p1 = p1->next->next;
                p2 = p2->next;
            }
        }
        
        p1 = p2;
        p2 = p2->next;
        p1->next = NULL;
        
        front = sortList(head);
        back = sortList(p2);
        return merge(front, back);
    }
    
    ListNode* merge(ListNode* h1, ListNode*h2) {
        ListNode *res, *p;
        if (h1 == NULL) return h2;
        if (h2 == NULL) return h1;
        
        if (h1->val < h2->val) {
            res = h1;
            h1 = h1->next;
        } else {
            res = h2;
            h2 = h2->next;
        }
        
        p = res;
        while (h1 != NULL && h2 != NULL) {
            if (h1->val < h2->val) {
                p->next = h1;
                h1 = h1->next;
            } else {
                p->next = h2;
                h2 = h2->next;
            }
            p = p->next;
        }
        
        if (h1 != NULL) p->next = h1;
        else if (h2 != NULL) p->next = h2;
        return res;
    }
};

以上是关于c_cpp 递归合并的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp Fibonacci与递归

c_cpp 递归冒泡排序

c_cpp 递归四面体

c_cpp 冒泡排序 - 递归

c_cpp 递归星2机问题

c_cpp 递归C插入排序