其他分享
首页 > 其他分享> > 剑指offer 016、合并两个排序的链表

剑指offer 016、合并两个排序的链表

作者:互联网

剑指offer 016、合并两个排序的链表

题目

image-20210912174343209

题解

迭代去做

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
        if(pHead1 == nullptr) return pHead2;
        if(pHead2 == nullptr) return pHead1;
        
        ListNode* newHead = (ListNode*)malloc(sizeof(struct ListNode));
        ListNode* node = newHead;
        
        while (pHead1 && pHead2) {
            if (pHead1->val < pHead2->val) {
                node->next = pHead1;
                pHead1 = pHead1->next;
            }
            else {
                node->next = pHead2;
                pHead2 = pHead2->next;
            }
            node = node->next;
        }
        
        node->next = (pHead1 ? pHead1 : pHead2);
        return newHead->next;
    }
};

递归版本

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

标签:ListNode,016,val,offer,next,链表,pHead1,pHead2,return
来源: https://blog.csdn.net/qq_45893475/article/details/120253637