c++ one pass solution


  • 0
    H
    class Solution {
    public:
        ListNode* reverseBetween(ListNode* head, int m, int n) {
            if(!head || !head->next) return head;
            ListNode* tmp_head = new ListNode(0);
            tmp_head->next = head;
            int cnt = 1;
            ListNode* pre = tmp_head;
            while(cnt != m) {
                pre = pre->next;
                cnt ++;
            }
            ListNode* cur = pre->next, * nxt = pre->next->next;
            while(cnt != n) {
                ListNode* tmp = nxt->next;
                nxt->next = cur;
                cur = nxt;
                nxt = tmp;
                cnt ++;
            }
            pre->next->next = nxt;
            pre->next = cur;
            return tmp_head->next;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.