I recently started reading about Linked Lists and I have a couple of questions. Before I start asking, let me post the ListNode class:
Pretty straightforward. Next, there is the LinearLinkedList class:Code:package linkedLists;
public class ListNode {
private Object value;
private ListNode next;
public ListNode(Object value, ListNode next) {
this.value = value;
this.next = next;
}
public Object getValue() {
return value;
}
public ListNode getNext() {
return next;
}
public void setValue(Object value) {
this.value = value;
}
public void setNext(ListNode next) {
this.next = next;
}
}
Question 1: addFirst()Code:package linkedLists;
public class LinearLinkedList {
ListNode firstNode;
public LinearLinkedList() {
firstNode = null;
}
public boolean isEmpty() {
return firstNode == null;
}
public ListNode getFirstNode() {
return firstNode;
}
public void setFirstNode(ListNode node) {
firstNode = node;
}
public void addFirst(Object o) {
if (isEmpty())
firstNode = new ListNode(o, null);
else {
//[I]implementation shown below[/I]
}
}
public void addLast(Object o) {
if (isEmpty())
firstNode = new ListNode (o, null);
else {
//[I]implementation shown below[/I]
}
}
[I]...other codes will be implemented later. (not in this thread)[/I]
}
The book implements the missing code like this:
When I did it, I did another way:Code:firstNode = new ListNode(o, firstNode);
The question is, are those two similar?Code:ListNode first = new ListNode(o, null);
first.setNext(firstNode.getNext());
firstNode = first;
Question 2: addLast()
The book implements the missing code like this:
Mine on the other hand, gets a null pointer access (yellow underline in eclipse. The underlined word is "current" in "current.setNext(new ListNode(o, null));"Code:ListNode current = firstNode;
while (current.getNext() != null)
current = current.getNext();
current.setNext(new ListNode(o, null));
Why am I getting the null pointer access? Also, why doesn't the book's code have the following:Code:while ((current = current.getNext()) != null);
[U]current[/U].setNext(new ListNode(o, null));
firstNode = current;
Don't I need to reference firstNode to current because current is a local variable?Code:firstNode = current;
Thanks in advance!!

