A c++ solution by adding a guard node


  • 0
    P
    class Solution {
    public:
    	ListNode *reverseBetween(ListNode *head, int m, int n) {
    		if (head == 0 || m == n)
    			return head;
    		ListNode* trivial_head = new ListNode(0);
    		trivial_head->next = head;
    		int counter;
    		ListNode *pre, *rbegin, *r, *rnext;
    		for (counter = 0, r = trivial_head; counter < m - 1; counter++)
    			r = r->next;
    		pre = rbegin = r;
    		for (r = r->next, rnext = r->next, counter = m; counter < n; counter++)
    		{
    			r->next = rbegin;
    			rbegin = r;
    			r = rnext;
    			rnext = r->next;			
    		}
    		pre->next->next = rnext;
    		r->next = rbegin;
    		pre->next = r;
    		return trivial_head->next;
    	}
    };

Log in to reply
 

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