iterative java solution without dummy node


  • 0

    '''
    public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
    if(head == null || head.next == null) return head;
    ListNode left = head, firstEnd = null;
    for(int i = 0; i < m - 1; i ++) {
    firstEnd = left;
    left = left.next;
    }
    ListNode cur = left;
    for(int j = 0; j < n - m; j ++) {
    cur = cur.next;
    }
    ListNode firstStart = cur.next;
    cur.next = null;
    ListNode sub = reverse(left);
    if(firstEnd == null) {
    left.next = firstStart;
    return sub;
    }
    firstEnd.next = sub;
    left.next = firstStart;
    return head;
    }
    private ListNode reverse(ListNode head) {
    if(head == null || head.next == null) return head;
    ListNode sub = reverse(head.next);
    head.next.next = head;
    head.next = null;
    return sub;
    }
    }
    '''


Log in to reply
 

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