Simple Java solution in place


  • 0
    C
    public class Solution {
        public ListNode reverseBetween(ListNode head, int m, int n) {
            if (head == null || head.next == null) {
                return head;
            }
            ListNode prev = new ListNode(0);
            prev.next = head;
            ListNode result = prev;
            for (int i = 1; i < m; i++) {
                prev = prev.next;
            }
            ListNode current = prev.next.next;
            ListNode tail = prev.next;
            int index = m + 1;
            while (current != null && index <= n) {
                ListNode temp = current.next;
                tail.next = temp;
                current.next = prev.next;
                prev.next = current;
                current = temp;
                index++;
            }
            return result.next;
        }
    }

Log in to reply
 

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