剑指 offer acwing 36 合并两个排序的链表

题面

在这里插入图片描述

题解

本题考查两路归并,我们可以用两个指针,新开一个虚拟节点,通过比较两个链表值的大小来移动指针,最后肯定有一个链表的指针到最后,然后将剩下一个链表的值复制即可

代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    
    
public:
    ListNode *merge(ListNode *l1, ListNode *l2) {
    
    

        ListNode *dummy = new ListNode(-1);
        auto cur = dummy;
        while (l1 && l2) {
    
    
            if (l1->val < l2->val) {
    
    
                cur->next = l1;
                 l1 = l1->next;
            } else {
    
    
                cur->next = l2;
                l2 = l2->next;
            }
            cur = cur->next;
        }

        while (l1) cur->next = l1, l1 = l1->next, cur = cur->next;
        while (l2) cur->next = l2, l2 = l2->next, cur = cur->next;

        return dummy->next;

    }
};

猜你喜欢

转载自blog.csdn.net/qq_44791484/article/details/115034604