leetcode 反转链表II 中等

leetcode 反转链表II 中等

 

 

 由于 left 的值可能为 1,所以用一个虚拟节点,其 next 之前 head,来作为一个哑结点。接下来只需要找到 left 和 right 位置的节点,然后进行反转即可。

class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int left, int right) {
        ListNode *tmpHead = new ListNode;
        tmpHead -> next = head;
        
        ListNode *pre = tmpHead;
        while(-- left > 0) {
            -- right;
            pre = pre -> next;
            head = head -> next;
        }
        while(-- right > 0) {
            head = head -> next;
        }
        auto nxt = head -> next;
        head -> next = nullptr;    // 指向 nullptr, 让其能够在 reverse 中正常结束
        pre -> next = reverse(pre -> next, nxt);
        auto ret = tmpHead -> next;
        delete tmpHead;
        return ret;
    }

private:
    ListNode *reverse(ListNode *head, ListNode *nxt) {
        ListNode *pre = nxt;
        while(head) {
            auto tmp = head -> next;
            head -> next = pre;
            pre = head;
            head = tmp;
        }
        return pre;
    }
};

 

leetcode 反转链表II 中等

上一篇:SRV05-4二极管ESD,SOT-23-6L封装,5V电压


下一篇:SharedPreferences