LeetCode第 99 题:反转链表 II(C++)

92. 反转链表 II - 力扣(LeetCode)

链表反转,重点就是要维护现场

记得使用dummy节点简化判断

class Solution {
public:
    void reverse(ListNode *left, ListNode *right){
        ListNode* pre = left->next, *cur = pre->next;
        pre->next = right;
        while(cur != right){
            auto tmp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = tmp;
        }
        left->next = pre;
    }
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        if(m == n) return head;
        auto dummy = new ListNode(-1);
        dummy->next = head;
        auto p = dummy;
        while(m > 1){
            p = p->next;
            --m;--n;
        }
        auto left = p;//left为第m个节点的前驱
        while(n >= 0){
            p = p->next;
            --n;
        }
        auto right = p;//right为第n个节点的后缀
        //开始反转操作
        reverse(left, right);
        return dummy->next;
    }
};

也可以使用递归函数,关于递归这位同学的讲解写的很清晰:

步步拆解:如何递归地反转链表的一部分 - 反转链表 II - 力扣(LeetCode)

猜你喜欢

转载自blog.csdn.net/qq_32523711/article/details/107848808