Share My 4ms C++ solution


  • 0
    P

    here p0 is used to record the pos of m-1.
    p2 is the node to be inserted to the pos of m.
    p1 is the previous node of p2

    class Solution {
    public:
        ListNode *reverseBetween(ListNode *head, int m, int n) {
            //make a head by myself
            ListNode *newHead=new ListNode(0);
            newHead->next=head;
            ListNode *p0=newHead;
            ListNode *p1=nullptr,*p2=nullptr;
            int i;
            //find position of p0
            for(i=1;i<m;i++)
                p0=p0->next;
            p1=p0->next;
            //reverse one by one
            while(i<n)
            {
                p2=p1->next;
                p1->next=p2->next;
                p2->next=p0->next;
                p0->next=p2;
                i++;
            }
            
            // p is the true head
            
            ListNode *p=newHead->next;
            delete newHead;
            return p;
        }
    };

Log in to reply
 

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