share my java solution


  • 0
    O
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode reverseBetween(ListNode head, int m, int n) {
            if(head == null) return null;
            ListNode root = head;
            ListNode pre = null;
            int count = 0;
            while(head != null && count < m-1){
                pre = head;
                head = head.next;
                count++;
            }
            if(pre != null) pre.next = reverse(head, n-m+1);
            else return reverse(head, n-m+1);
            return root;
        }
    
        // reverse the first k elements of a linkedlist
        public ListNode reverse(ListNode head, int k) {
            ListNode pre = null;
            ListNode tail = head;
            ListNode nxt = null;
            int count = 0;
            while(head != null && count < k){
                count++;
                ListNode next = head.next;
                nxt = head.next;
                head.next = pre;
                pre = head;
                head = next;
            }
            if(tail != null) tail.next = nxt;
            if(pre == null) return head;
            return pre;
        }
    }
    

Log in to reply
 

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