Sobes.tech
Junior — Middle+

Moving the counter to the first node of the list

livecode

Task condition

Optimize the list implementation so that the counter field is only present in the head element and not duplicated in other nodes. It is necessary to modify the current code, where each ListNode stores its own counter, and ensure that the counter is incremented only when the first node is created.

public class ListNode<T> implements Node<T> {

    private T value;
    private ListNode<T> next;

    // store only in the head node
    private int counter;

    public ListNode(T value) {
        this.value = value;
        counter++;
    }

    public ListNode() {
    }
}