My 0ms C++ code


  • 0
    Z
    /**
     * 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) return head;
            ListNode* p = head,*pq = NULL,*pm = NULL;
            int i = 1;
            if(m==1)
            {
                pq = p->next;
                while(++i<=n)
                {
                    pm=pq->next;
                    pq->next = p;
                    p=pq;
                    pq=pm;
                }
                head->next=pq;
                return p;
            }
            else
            {//1->2->3->4->5->NULL  here, pa ->1 p->2,
                ListNode*pa = head;
                int i = 1;
                while(++i<m)
                    pa = pa->next;
                p = pa->next;
                ListNode*pc=p;
                pq = p->next;
                i = 0;
                while(++i<=n-m)
                {
                    pm=pq->next;
                    pq->next = p;
                    p=pq;
                    pq=pm;
                }
                pc->next = pq;
                pa->next=p;
                return head;
                
            }
            
            
            
        }
    };`enter code here`

Log in to reply
 

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