My Java solution 0ms


  • 0
    E
    public class Solution {
        public ListNode reverseBetween(ListNode head, int m, int n) {
            if (head == null) {
                return null;
            }
            
            int count = 1;
            ListNode prevNode = head;
            ListNode currNode = head;
            
            // Loop until m is reached
            while (count < m) {
                prevNode = currNode;
                currNode = currNode.next;
                count++;
            }
                    
            // saves node M
            ListNode nodeM = currNode;
            ListNode nextNode = currNode.next;
            ListNode loopNode;
            
            // Reverse node between m and n
            while(count < n) {
                loopNode = nextNode.next;
                nextNode.next = currNode;
                currNode = nextNode;
                nextNode = loopNode;
                count++;
            }
            prevNode.next = currNode;
            nodeM.next = nextNode;
            
            if (m == 1) {
                head = currNode;
            }
            return head;
        }
    }

  • 0
    J

    one pass please


Log in to reply
 

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