My c++ solution ,easy to understand 4ms


  • 0
    W
    class Solution {
    public:
        ListNode* reverseBetween(ListNode* head, int m, int n) {
            if(head==NULL)
            return head;
          ListNode head1(0);
          head1.next=head;
          ListNode *p=&head1;
          ListNode *q=&head1;
          ListNode *prep,*r;
          int count=0;
          while(count<n)
          {
              q=q->next;
              if(count>=(n-m))
              {
                 prep=p;
                 p=p->next;
              }
              count++;
          }
          prep->next=q->next;
          while(p!=q)
          {
              r=p->next;
              p->next=prep->next;
              prep->next=p;
              p=r;
          }
          p->next=prep->next;
          prep->next=p;
          return head1.next;
        }
    };

Log in to reply
 

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