0
点赞
收藏
分享

微信扫一扫

图示 LeetCode: 92. 反转链表 II

书写经典 2022-05-06 阅读 54

题目: 92. 反转链表 II

class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int left, int right) {
        if(!head || left == right) return head;

        ListNode  lst;
        lst.next = head;
        head = &lst;
        // 增加一个前驱节点,简化后续判断
        ListNode* frontlinked = head; 

        for(int i = 1; i != left; ++i){
            frontlinked = frontlinked->next;
        }

        ListNode* prev = frontlinked, *cur = frontlinked->next, *next = nullptr;
        for(int i = left; i != right; ++i){
            next = cur->next;
            cur->next = next->next;
            next->next = prev->next;
            prev->next = next;
        }
        
        return lst.next;
    }
};

循环内部链接图示

cur -> next = next->next

next->next = frontlinked->next

frontlinked->next = next

举报

相关推荐

0 条评论