Sobes.tech
Junior — Middle

Como determinar antes do último elemento numa lista ligada simples?

sobes.tech IA

Resposta da IA

Numa lista ligada simples, para encontrar o elemento antes do último, é necessário percorrer a lista e parar no nó cujo próximo nó é o último (ou seja, cujo campo Next do próximo nó é null).

Exemplo em C#:

class Node {
    public int Value;
    public Node Next;
}

Node FindPenultimate(Node head) {
    if (head == null || head.Next == null) return null; // não há penúltimo
    Node current = head;
    while (current.Next.Next != null) {
        current = current.Next;
    }
    return current;
}

Aqui, o ciclo continua enquanto o próximo nó tiver um próximo, ou seja, até chegar ao penúltimo elemento.