simple C++ solution


  • 1
    _

    Re: Share my 14 lines C++ solution
    modify above solution, using pointer to pointer, not to creat a prehead;

      ListNode* reverseBetween(ListNode* head, int m, int n) {
          if(m==n) return head;
          ListNode **phead = &head; //pointer to head
          ListNode **pp = &head;
          n = n-m;
          while(--m) pp = &((*pp)->next); // find the start
          ListNode *pStart = *pp;
          ListNode *pNext = nullptr;
          while(n--) {
              pNext = pStart->next;
              pStart->next = pNext->next;
              pNext->next = *pp;
              *pp = pNext;
          }
          return *phead;
      }
    

Log in to reply
 

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