Reverse Linked List II

Reverse a linked list from position m to n. Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ length of list.

Example:

Given 1->2->3->4->5->NULL, m = 2 and n = 4, return 1->4->3->2->5->NULL.

Challenge:

Reverse it in-place and in one-pass

Solution:

  1. Find the node who is previous to m-th node (prevM)
  2. Iterate through from m-th node to n-th node, reverse them.
  3. Attach tail (n +1 th node ) to prevM.next (old m-th node) and prevM.next to reversed head.

Code:

/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param ListNode head is the head of the linked list 
     * @oaram m and n
     * @return: The head of the reversed ListNode
     */
    public ListNode reverseBetween(ListNode head, int m , int n) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode prevM = dummy;
        for (int i = 1; i < m; i++) {
            prevM = prevM.next;
        }
        ListNode prev = prevM;
        ListNode curt = prevM.next; //this is m-th node
        for (int i = m; i <= n; i++) {
            ListNode temp = curt.next;
            curt.next = prev;
            prev = curt;
            curt = temp;
        }
        //attach n to m - 1
        prevM.next.next = curt;
        //attach n + 1 to m
        prevM.next = prev;
        return dummy.next;
    }
}

results matching ""

    No results matching ""