Insertion into Doubly linked list

Nikita picture Nikita · Oct 25, 2011 · Viewed 7.9k times · Source

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.

Answer

matt b picture matt b · Oct 25, 2011

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?