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

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

题目

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

题解

迭代去做

/*
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;
        }
    }
};
上一篇:BUUCTF 每日打卡 2021-5-21


下一篇:uniapp使用picker报错Error in render: "TypeError: Cannot read property 'XXX' of undefined&