I think I'm having trouble with my Queue class because I know using a Queue uses the FIFO method, but want to make sure that when I add an element that it is added at the end of the Queue. In my main program I have added numbers 1-4, but when I want to print my entire Queue using the toString method in my Queue class it will only print out the first element which is 1. I would appreciate some help!
Thank you!
public class QuestionFive
{
public static void main(String[] args)
{
// creating a queue
Queue q = new Queue();
// adding numbers 1,2,3 and 4
q.insert(1);
q.insert(2);
q.insert(3);
q.insert(4);
System.out.println(q);
}
}
class Queue
{
//Private Data Member
private Link _head;
//Constructor: A constructor to create an empty Queue,
public Queue()
{
_head = null;
}
//Insert Method: A method to insert a given Object into the Queue.
//Note: We will inserton
public void insert(Object item)
{
Link add = new Link();
add.data = item;
add.next = null;
if(_head == null)
{
_head = add;
}
else
{
for(Link curr = _head; curr.next != null; curr = curr.next)
{
curr.next = add;
}
}
}
//Delete Method: A method to delete an Object from the Queue
public Object delete()
{
if ( _head == null ) return null;
Link prev = null;
Link curr = _head;
while (curr.next != null )
{
prev = curr;
curr = curr.next;
}
if ( prev != null )
{
prev.next = null;
}
else
{
_head = null;
}
return curr.data;
}
// IsEmpty Method: A method to test for an empty Queue
public boolean isEmpty()
{
// queue is empty if front is null
return (_head == null);
}
//toString Method:
public String toString()
{
String s = "";
for (Link curr = _head; curr != null; curr = curr.next)
{
s = s + " " + curr.data;
}
return s;
}
}
//Link Class
class Link
{
public Object data;
public Link next;
}