16、合并两个有序链表 过,可以不再刷了

示例1
输入

{1,3,5},{2,4,6}

返回值

{1,2,3,4,5,6}

力扣上有类似的题目了

1、常规做法,非递归花了好久才做出来
struct ListNode {
    int val;
    struct ListNode* next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
}; 


ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
       if (pHead1 == nullptr) return pHead2;
    if (pHead2 == nullptr) return pHead1;

    ListNode* Head = (ListNode*)malloc(sizeof(struct ListNode));

    if (pHead1->val <= pHead2->val) {
        Head = pHead1;
        pHead1 = pHead1->next;
    }else {
        Head = pHead2;
        pHead2 = pHead2->next;
    }

    ListNode* node = (ListNode*)malloc(sizeof(struct ListNode));
    node = Head;

    while (pHead1 && pHead2) {
        if (pHead1->val <= pHead2->val) {
            node->next = pHead1;
            pHead1 = pHead1->next;
            node = node->next;
        }
        else {
            node->next = pHead2;
            pHead2 = pHead2->next;
            node = node->next;
        }

    }
    if (pHead1 != nullptr) {
        node->next = pHead1;
    }
    else {
        node->next = pHead2;
    }
    return Head;
    }


    void test02()
{
    ListNode* head = (ListNode*)malloc(sizeof(ListNode));
    head->val = 1;

    ListNode* node1 = (ListNode*)malloc(sizeof(ListNode));
    node1->val = 5;

    ListNode* node2 = (ListNode*)malloc(sizeof(ListNode));
    node2->val = 9;

    ListNode* node3 = (ListNode*)malloc(sizeof(ListNode));
    node3->val = 11;
    //node3->next = NULL;

    head->next = node1;
    node1->next = node2;
    node2->next = node3;
    node3->next = nullptr;


    ListNode* head2 = (ListNode*)malloc(sizeof(ListNode));
    head2->val = 3;

    ListNode* node12 = (ListNode*)malloc(sizeof(ListNode));
    node12->val = 3;

    ListNode* node22 = (ListNode*)malloc(sizeof(ListNode));
    node22->val