Reverter parte da lista ligada

Descrição do título:

Inverta a lista vinculada da posição m para n. Use uma varredura para concluir a reversão.

Explicação:
1 ≤ m ≤ n ≤ comprimento da lista vinculada.

Exemplo:
Entrada: 1-> 2-> 3-> 4-> 5-> NULL, m = 2, n = 4
Saída: 1-> 4-> 3-> 2-> 5-> NULL

código mostrado abaixo:

Analise de problemas

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    
    
    public ListNode reverseBetween(ListNode head, int left, int right) {
    
    
        ListNode dummyNode = new ListNode();
        dummyNode.next = head;
        ListNode pre = dummyNode;
        for (int i = 0; i < left - 1; i++) {
    
    
            pre = pre.next;
        }
        ListNode cur = pre.next;
        ListNode next;
        for (int i = 0; i < right - left; i++) {
    
    
            next = cur.next;
            cur.next = next.next;
            next.next = pre.next;
            pre.next = next;
        }
        return dummyNode.next;
    }
}

Resultados de:
Insira a descrição da imagem aqui

Acho que você gosta

Origin blog.csdn.net/FYPPPP/article/details/114964529
Recomendado
Clasificación