Skip to content
  • Sponsor bobocode-projects/java-fundamentals-exercises

  • Notifications You must be signed in to change notification settings
  • Fork 493

2-2-4-linked-list, add tests accept the broken code #166

Open
@obaibula

Description

@obaibula

The broken code:

private void addAsHead(Node<T> newNode) {
        newNode.next = head;
        head = newNode;
}

Please consider the following example:

LinkedList<Integer> list = new LinkedList<>();
        list.add(0, 100);
        list.add(144);

This code will result in a NullPointerException if we define the add method as follows:

@Override
    public void add(T element) {
        requireNonNull(element);
        Node<T> newNode = new Node<>(element);

        if(head == null){
            head = tail = newNode;
        } else {
            tail.next = newNode;
            tail = tail.next;
        }
        size++;
    }

It's necessary to reassign tail, as shown in the "completed" branch.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      2-2-4-linked-list, add tests accept the broken code · Issue #166 · bobocode-projects/java-fundamentals-exercises