【LeetCode】1669. 合并两个链表

/**
 * 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* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) {
        ListNode* beforePa, *afterPb, *p1, *p2, *lastP2;
        p1 = list1; // 没有头节点的单链表
        p2 = list2;
        int num = 0;
        while(p1 != nullptr)
        {
            if(num == a-1) beforePa = p1;
            if(num == b+1) 
            {
                afterPb = p1;
                break;
            }
            num++;
            p1 = p1->next;
        }
        beforePa->next = p2;
        while(p2!=nullptr)
        {
            if(p2->next == nullptr) lastP2 = p2;
            p2 = p2->next;
        }
        lastP2->next = afterPb;

        return list1;
    }
};
posted @ 2023-01-30 09:59  小超不挑食  阅读(2)  评论(0编辑  收藏  举报