Java straight forward solution


  • 0
    T
    public ListNode reverseBetween(ListNode head, int m, int n) {
        ListNode current = head;
        ListNode reverseHead = null;
        ListNode dummy = null;
        ListNode tail = new ListNode(0);
        for (int i = 1; i <= n; i++) {
            if (i == m - 1) {
                reverseHead = current;
            } else if (i >= m) {
                if (i == m)
                    tail = current;
                ListNode node = current;
                current = current.next;
                node.next = dummy;
                dummy = node;
                continue;
            }
            current = current.next;
        }
        tail.next = current;
        if (reverseHead == null)
            return dummy;
        else
            reverseHead.next = dummy;
        return head;
    }

Log in to reply
 

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