Categorías
Algorithms Interview

LeetCode – Lista vinculada inversa II (Java)

Invierta una lista enlazada de la posición m a la n. Hágalo en el lugar y en una sola pasada.

Por ejemplo: dado 1-> 2-> 3-> 4-> 5-> NULL, m = 2 y n = 4, devuelve 1-> 4-> 3-> 2-> 5-> NULL.

Análisis

Solución Java

public ListNode reverseBetween(ListNode head, int m, int n) {
    if(m==n) return head;
 
    ListNode prev = null;//track (m-1)th node
    ListNode first = new ListNode(0);//first's next points to mth
    ListNode second = new ListNode(0);//second's next points to (n+1)th
 
    int i=0;
    ListNode p = head;
    while(p!=null){
        i++;
        if(i==m-1){
            prev = p;
        }
 
        if(i==m){
            first.next = p;
        }
 
        if(i==n){
            second.next = p.next;
            p.next = null;
        }
 
        p= p.next;
    }
    if(first.next == null)
        return head;
 
    // reverse list [m, n]    
    ListNode p1 = first.next;
    ListNode p2 = p1.next;
    p1.next = second.next;
 
    while(p1!=null && p2!=null){
        ListNode t = p2.next;
        p2.next = p1;
        p1 = p2;
        p2 = t;
    }
 
    //connect to previous part
    if(prev!=null)
        prev.next = p1;
    else
        return p1;
 
    return head;
}
  LeetCode-Matriz Toeplitz

Por Programación.Click

Más de 20 años programando en diferentes lenguajes de programación. Apasionado del code clean y el terminar lo que se empieza. ¿Programamos de verdad?

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *