Sobes.tech
Junior — Middle

Kaip nustatyti prieš paskutinį elementą vienguboje susietoje sąraše?

sobes.tech AI

Atsakymas iš AI

Vienkryptėje susietoje sąraše, norint rasti priešpaskutinį elementą, reikia pereiti per sąrašą ir sustoti prie mazgo, kurio sekantis mazgas yra paskutinis (t. y., lauko Next reikšmė yra null).

Pavyzdys C#:

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

Node FindPenultimate(Node head) {
    if (head == null || head.Next == null) return null; // nėra priešpaskutinio
    Node current = head;
    while (current.Next.Next != null) {
        current = current.Next;
    }
    return current;
}

Čia ciklas tęsiasi tol, kol sekantis mazgas turi ir savo sekantį mazgą, t. y., kol nepasieksime priešpaskutinio elemento.