Easy-to-Understand C++ Submission


  • 0
    S
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *reverseBetween(ListNode *head, int m, int n) 
        {
            if(head==NULL || head->next==NULL || m==n) return head;
            ListNode *preFront,*front,*tail,*postTail,*pre,*cur,*post;
            preFront=NULL;
            front=head;
            while(--m)
            {
                preFront=front;
                front=front->next;
            }
            tail=head;
            postTail=head->next;
            while(--n)
            {
                tail=postTail;
                postTail=postTail->next;
            }
            pre=front;
            cur=pre->next;
            post=cur->next;
            while(cur!=postTail)
            {
                cur->next=pre;
                pre=cur;
                cur=post;
                if(post!=NULL) post=post->next;
            }
            if(preFront!=NULL) preFront->next=tail;
            else head=tail;
            front->next=postTail;
            return head;
        }
    };

Log in to reply
 

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