2

I have a problem with addition of elements in Liked List

public class LinkedList {
    public Node first;
    public Node last;

    public LinkedList() {
        first = null;
        last = null;
    }

    public void addFirst(Student student) {
        Node f = first;
        Node newNode = new Node(student);
        first = newNode;
        if (f == null) last = newNode;
        else f.previous = newNode;
    }

    public void addLast(Student student) {
        Node l = last;
        Node newNode = new Node(student);
        last = newNode;
        if (l == null) first = newNode;
        else {
            l.next = newNode;
        }
    }


    public void display() {
        Node current = first;
        while (current != null) {
            //print...
            current = current.next;
        }
    }

My problem is when I run:

list.addLast(1);
list.addFirst(2);
list.display();

It displays just "2" 'display' method just can't see last added element.
But if I run:

list.addFirst(2);
list.addLast(1);

It will display both. What is wrong with it? Thanks.

3 Answers 3

4

If this list is doubly-linked, shouldn't you be adding a reference in newNode to the elements that come before/after it?

Your display() method traverses node.next but in addFirst() you never set .next - so if you call addFirst() several times, and only that method, what will display() print?

Sign up to request clarification or add additional context in comments.

1 Comment

I get it, it will print just last added element.
2

in addFirst you also have to put newNode.next = f, right now you're just updating one side of the bidirectional relationship. And since the display uses the next field, it doesn't work as you expect it.

Similarly, in addLast you need to add newNode.previous = l, however since the previous field isn't used in the display method, it doesn't appear bugged when you execute it.

Comments

0
public void addFirst(Student student) {
    Node f = first;
    Node newNode = new Node(student);
    newNode.next = f; // this was missing
    first = newNode;
    if (f == null)
        last = newNode;
    else
        f.previous = newNode;
}

public void addLast(Student student) {
    Node l = last;
    Node newNode = new Node(student);
    newNode.previous = l; // this was missing
    last = newNode;
    if (l == null)
        first = newNode;
    else
        l.next = newNode;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.