[0-ms][recommended to beginners] C++ AC code with one submission


  • 0

    This problem is almost the same type, just as the reverse linked list 1 and the reverse the linked list by k groups . All of them call the same sub-function, and you just to make clear about the global logics.

    class Solution {
    public:
        ListNode* reverseBetween(ListNode* head, int m, int n) {
            if(!head)   return NULL;
            ListNode* dummy=new ListNode(-1), *cur;
            dummy->next=head;
            cur=dummy;
            for(int i=0; i<m-1; i++){
                cur=cur->next;
            }
            reverseList(cur, n-m+1);
            return dummy->next;
        }
        
        void reverseList(ListNode* head, int k){
            ListNode* start=head->next, *cur=start->next, *temp;
            int i=1;
            while(i<k){
                i++;
                start->next=cur->next;
                temp=head->next;
                head->next=cur;
                cur->next=temp;
                cur=start->next;
            }
            return;
        }
    };

  • 0

    The key idea behind the solution is just that you need to put node into the head place one by one ....


Log in to reply
 

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