Skip to content

Latest commit

 

History

History
executable file
·
63 lines (58 loc) · 1.4 KB

0092. Reverse Linked List II.md

File metadata and controls

executable file
·
63 lines (58 loc) · 1.4 KB

92. Reverse Linked List II, medium

Reverse a linked list from position m to n. Do it in one-pass.

Note: 1 ≤ m ≤ n ≤ length of list.

Example:

Input: 1->2->3->4->5->NULL, m = 2, n = 4 Output: 1->4->3->2->5->NULL

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        if (!head || m < 1 || n < 1)
            return head;
        int cc = 1;
        auto t = head;
        
        ListNode *mp = nullptr, *np = nullptr, *tp = nullptr;
        auto before = mp, after = np;
        while (t && cc <= n) {
            if (m == cc) {
                mp = t;
                before = tp;
            }
            if (n == cc) {
                np = t;
                after = t->next;
                break;
            }
            tp = t;
            t = t->next;
            cc++;
        }
        if (!mp || !np) return head;
        
        // reverse
        ListNode* next = nullptr;
        t = mp;
        while (t) {
            auto tn = t->next;
            t->next = next;
            if (t == np)
                break;
            next = t;
            t = tn;
        }
        if (before) {
            before->next = np;
        }
        mp->next = after;
        return m > 1? head : np;
    }
};