I'm fairly new to doubly linked lists and I'm having trouble with one of my methods that is supposed to add a new node to the front of the list. Whenever I'm trying to add to an empty list, it prints out what I wanted to add but it also prints out a null. Here is my code:
public class Box<E> {
private DoubleListNode<E> head;
private DoubleListNode<E> tail;
private int size;
public Box() {
head = new DoubleListNode<E>();
tail = head;
size = 0;
}
private static class DoubleListNode<E> {
private E myData;
private DoubleListNode<E> myNext;
private DoubleListNode<E> myPrev;
public DoubleListNode() {
this(null, null, null);
}
public DoubleListNode(DoubleListNode<E> prev, E data,
DoubleListNode<E> next) {
myData = data;
myNext = next;
myPrev = prev;
}
}
public void addFirst(E item) {
if (item == null) {
throw new IllegalArgumentException("The parameter"
+ "'item' does not meet the pre conditions.");
}
DoubleListNode<E> newNode = new DoubleListNode<E>(null, item, head);
newNode.myNext = head;
newNode.myPrev = null;
if (head != null) {
head.myPrev = newNode;
}
head = newNode;
size++;
}
public String toString() {
if (size == 0) {
return "[]";
}
StringBuilder sb = new StringBuilder("[");
sb.append(head.myData);
DoubleListNode<E> temp = head.myNext;
while (temp != null) {
sb.append(", ");
sb.append(temp.myData);
temp = temp.myNext;
}
return sb.append("]").toString();
}
public static void main(String[] arg) throws FileNotFoundException {
Box<Integer> dl = new Box<Integer>();
dl.addFirst(1);
System.out.println(dl);
}
}
Here in main, I added 1 to the list and it should print [1], but instead it's printing [1, null]
Box
constructor you create a node with a null value. – Garr Godfrey