Share my O(n) JAVA solution


  • 0
    W
    public class Solution {
        public ListNode reverseBetween(ListNode head, int m, int n) {
            ListNode preHead = new ListNode(0);
            preHead.next = head;
            
            ListNode node = preHead;
            while (m > 1){
                node = node.next;
                m--;
                n--;
            }
            ListNode tail = node.next;
            ListNode current = node.next.next;
            
            while (current != null && n > 1){
                ListNode tmp = node.next;
                node.next = current;
                current = current.next;
                node.next.next = tmp;
                tail.next = current;
                n--;
            }
            
            return preHead.next;
        }
    }

  • 0
    Z

    nice!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


Log in to reply
 

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