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.
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.