Assuming this is a FIFO queue and your SinglyLinkedNode
constructor is for the node's value and next node: you firstly need set the current tail to point to the new tail, then secondly to set the tail to point to the new tail:
public void enqueue(String str) {
// Empty queue
if (isEmpty()) {
head = new SinglyLinkedNode(str, null);
tail = head;
}
// Non-empty queue
else {
SinglyLinkedNode newTail = new SinglyLinkedNode(str, null);
tail.next = newTail;
tail = newTail;
}
}
Note that it doesn't make a lot of sense to set the head and tail as separate nodes with an empty String (they are different instances of SinglyLinkedNode
). Instead your declaration of fields in SinglyLinkedQueue
should be:
private SinglyLinkedNode head, tail;
Head and tail are just pointers to a particular node(s). You just need to keep them updated as you modify the queue (and of course ensure you keep your nodes all linked appropriately).
Lastly for iterative toString()
as pointed out by Ted Bigham:
@Override
public String toString() {
if (isEmpty()) {
return "";
}
String result = "<";
SinglyLinkedNode current = head;
while (current != null) {
result += current.value;
current = current.next;
if (current != null) {
result += ",";
}
}
return result + ">";
}
Though I think it would be better to return <>
for empty queue instead as it is more informative and simplifies the code.
Note also the @Override
annotation should be used as you are overriding the default toString()
method. Why it is useful is indicated here.