simple solution,O(n) time O(1) space


  • 0
    Z
    class Solution {
    public:
        ListNode* reverseBetween(ListNode* head, int m, int n) {
            ListNode h(0);
            h.next = head;
            ListNode* p = &h;
            for(int i=1;i<m;++i,p = p->next);
            ListNode* t = p->next;
            for(int i=0;i<n-m;++i)
            {
                ListNode* tmp = t->next;
                t->next = t->next->next;
                tmp->next = p->next;
                p->next = tmp;
            }
            return h.next;
            
        }
    };

Log in to reply
 

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