My accepted Java solution


  • 0
    B
    public class Solution {
        public ListNode reverseBetween(ListNode head, int m, int n) {
            if(head == null || head.next == null || m >= n){
                return head;
            }
            int count = 1;
            ListNode curr = head;
            ListNode pre = new ListNode(-1);
            pre.next = curr;
            
            ListNode hold = null;
            
            while(count <= m){
                if(count == m){
                    hold = pre;
                }
                pre = curr;
                curr = curr.next;
                count++;
            }
            
            ListNode post = curr.next;
            
            while(count <= n){
                curr.next = pre;
                pre = curr;
                curr = post;
                if(post != null){
                    post = post.next;
                }
                count++;
            }
            
            hold.next.next = curr;
            hold.next = pre;
            
            if(m == 1){
                return hold.next;
            }
            return head;
            
        }
    }

Log in to reply
 

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