92. Reverse Linked List II

Gold_stein發表於2024-10-07

92. Reverse Linked List II

在連結串列頭新增一個虛擬源點,可以減少特判

/**
 * 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* reverseBetween(ListNode* head, int left, int right) {
        if(right == left) {
            return head;
        }
        int cnt = 1;
        ListNode* cur = head;
        ListNode* prev = new ListNode(0, head), *next = nullptr, *vir = prev;
        while(cnt < left) {
            cnt++;
            prev = cur;
            cur = cur->next;
        }
        ListNode *L = prev, *L1 = cur;
        while(cnt <= right) {
            cnt++;
            if(cnt == right) {
                L->next = cur->next;
            }
            next = cur->next;
            cur->next = prev;
            prev = cur;
            cur = next;
        }
        if(cur)
            L1->next = cur;
        else 
            L1->next = nullptr;
        return vir->next;
    }
};

相關文章