My C++ Solution(4ms)


  • 0
    class Solution {
    public:
        ListNode* reverseBetween(ListNode* head, int m, int n) {
            if (m == n) return head;
    		ListNode* front = new ListNode(0);
    		front->next = head;                     // insert head node
    		head = front;
    		ListNode* phead = head, *prear = head->next;
    		m -= 1;
    		if(m)while (m--) phead = phead->next;  // m--
    		while (n--) prear = prear->next;       // n--
    		ListNode* pos = phead->next->next;
    		phead->next->next = prear;
    		ListNode* temp = nullptr;
    		while (pos != prear){
    			temp = pos->next;
    			pos->next = phead->next;
    			phead->next = pos;
    			pos = temp;
    		}
    		return front->next;
        }
    };

Log in to reply
 

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