Reverse Linked List II

Reverse a linked list from position m _to _n. Do it in one-pass.

Note: 1 ≤mn≤ length of list.

Example:

Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL

Solution

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if (head == null || head.next == null || m >= n) {
           return head; 
        }
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        head = dummy;
        for (int i = 1; i < m; i++) {
            if (head == null) {
                return null;
            }
            head = head.next;
        } 
        ListNode prevNode = head;
        ListNode tailNode = head.next;
        ListNode curr = head.next;
        prevNode.next = null;
        for (int i = m; i <= n; i++) {
            if (i == n) {
               tailNode.next = curr.next; 
            }
            ListNode nextNode = curr.next;    
            curr.next = prevNode.next;
            prevNode.next = curr;
            curr = nextNode;
        }
        return dummy.next;
    }
}

Last updated