Java solution


  • 0
    N
    public ListNode reverseBetween(ListNode head, int m, int n) {
            if (head == null || head.next == null) {
                return head;
            }
            ListNode newHead = new ListNode(0);
            newHead.next = head;
            ListNode pre;
            ListNode p = newHead;
            for (int i = 1; i < m; i++) {
                p = p.next;
            }
            pre = p;
            int gap = n - m;
            ListNode reverseHead = pre.next.next, reverserPre = pre.next;
            while (gap > 0 && reverseHead != null) {
                gap--;
                ListNode next = reverseHead.next;
                reverseHead.next = reverserPre;
                reverserPre = reverseHead;
                reverseHead = next;
            }
            pre.next.next = reverseHead;
            pre.next = reverserPre;
            return newHead.next;
        }
    

Log in to reply
 

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