Leetcode|剑指offer25/21. 合并两个有序链表

2021-09-18 17:25:35 浏览数 (1)

1 迭代法

代码语言:javascript复制
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        auto head = new ListNode();
        auto preNode = head;
        auto first = l1, second = l2;
        while (first && second) {
            if (first->val < second->val) {
                preNode->next = first;
                first = first->next;
            } else {
                preNode->next = second;
                second = second->next;
            }
            preNode = preNode->next;
        }
        // 若是因为first为空导致退出while,则说明second链表还有剩余,尾部添加second即可,反之亦然
        preNode->next = !first ? second : first;
        return head->next;
    }
};

0 人点赞