I am working on a homework assignment involving linked lists. We have to implement a queue ADT, and the one method I am having trouble with is adding a node to the end of the list (the enqueue method). Here is my code:
public class Queue implements QueueInterface {
private Node head;
private Node tail;
private int sz;
public Queue() {
head = null;
tail = null;
sz = 0;
}
public void enqueue(T newEntry) {
Node newElement = new Node(newEntry);
newElement.next = null;
tail.next = newElement;
tail = newElement;
}
public T dequeue() {
T result = null;
if(head != null) {
result = head.data;
head = head.next;
sz--;
}
return result;
}
public T getFront() {
return head.data;
}
public boolean isEmpty() {
if (head == null) {
return true;
}
return false;
}
public void clear() {
while (!isEmpty()) {
dequeue();
}
}
@Override
public String toString() {
return "Queue [head=" + head + ", sz=" + sz + "]";
}
public class Node {
private Node next;
private T data;
public Node (T newData) {
data = newData;
}
@Override
public String toString() {
return "Node [next=" + next + ", data=" + data + "]";
}
}
}
If anyone could help me out with this I would be really appreciative. Thanks for your time! 🙂
You aren’t handling the case where the list is empty. You’re adding the first item,
tailisnulland you’re getting the appropriate exception.You need to check
tailto see if it’snullbefore attempting to use it, and act appropriately if that is the case. Don’t forget to setheadas well.