合并两个排序的链表

合并两个排序的链表

题目描述

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

归并排序的变形

递归版

class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
        ListNode *ret = NULL;
        
        if (NULL == pHead1) {
            return pHead2;
        }
        else if (NULL == pHead2) {
            return pHead1;
        }
        
        if (pHead1->val < pHead2->val) {
            ret = pHead1;
            ret->next = Merge(pHead1->next, pHead2);
        }
        else {
            ret = pHead2;
            ret->next = Merge(pHead1, pHead2->next);
        }
        
        return ret;
    }
};

非递归: 注意头结点保存方法, 先new一个节点做头结点, 归并后再delete

class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
        ListNode *ret = new ListNode(0);
        ListNode *current = ret;
        
        while ((NULL != pHead1) && (NULL != pHead2)) {
            if (pHead1->val < pHead2->val) {
                current->next = pHead1;
                pHead1 = pHead1->next;
            }
            else {
                current->next = pHead2;
                pHead2 = pHead2->next;
            }
            current = current->next;
        }
        
        if (NULL == pHead1) {
            current->next = pHead2;
        }
        if (NULL == pHead2) {
            current->next = pHead1;
        }
        
        current = ret->next;
        delete ret;
        ret = current;
        
        return ret;
    }
};
/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
posted @ 2019-02-27 15:08  张飘扬  阅读(90)  评论(0编辑  收藏  举报