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
/**
 * 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 || m >= n ){
            return head;
        }
        
        
        ListNode dummy = new ListNode(-1);
        
        dummy.next = head;
        
        head = dummy;
        
        for(int i = 0; i < m-1; i++){
            if(head == null) 
                return null;
            
            head = head.next;
        }
        
        ListNode pre = null, next = null, cur = head.next;
        
        for(int i = 0; i < (n - m +1);i++){
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        
        head.next.next = cur;
        head.next = pre;
        
        return dummy.next;
        
   
    }
    
    
}

Last updated