C# Solution


  • 0
        public ListNode ReverseBetween(ListNode head, int m, int n) {
            if (head == null || head.next == null)
                return head;
            
            ListNode dummyNode = new ListNode(-1), 
                     tempTailInOriginal = null, 
                     tempTailInReverse = null, 
                     tempNode1 = null, 
                     tempNode2 = null, 
                     tempNode3 = null;
            
            dummyNode.next = head;
            tempTailInOriginal = dummyNode;
            
            for (int i = 1; i < m; i++)
                tempTailInOriginal = tempTailInOriginal.next;
                
            tempTailInReverse = tempTailInOriginal.next;
            
            tempNode1 = tempTailInOriginal.next;
            tempNode2 = tempNode1.next;
            if (tempNode2 != null)
                tempNode3 = tempNode2.next;
            
            for (int i = 1; i <= n - m; i++)
            {
                tempNode2.next = tempNode1;
                tempNode1 = tempNode2;
                tempNode2 = tempNode3;
                if (tempNode2 != null)
                    tempNode3 = tempNode2.next;
            }
            
            tempTailInOriginal.next = tempNode1;
            tempTailInReverse.next =tempNode2;
            
            return dummyNode.next;
        }

Log in to reply
 

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