I'm trying to make a linked list implementation of a queue in Java and in my driver program after I dequeue some elements, the size is not adjusting to be a lower number like it should. Here's the code and the output is below it.
This is the linked list queue implementation:
import java.util.LinkedList;
//implementation of a queue by using a linked list
public class Queue<T> {
//declaring array list to store and manipulate data
//using predefined methods
private LinkedList<T> list;
int count, front, rear;
public Queue() {
list= new LinkedList<T>();
count=front=rear=0;
}
//Adds given element to rear of queue
public void enqueue (T element) {
if(front==rear) {
list.add(front, element);
rear++;
}
else {
list.add(rear, element);
rear++;
}
count++;
}
//removes element at queue front
public T dequeue() {
if(list.isEmpty()) {
System.out.println("Queue is empty");
return null;
}
T result = list.get(front);
front++;
count--;
return result;
}
//returns reference to element at queue front
public T first() {
return list.get(front);
}
//returns true if queue is empty
public boolean isEmpty() {
if(list.isEmpty())
return true;
else
return false;
}
//returns number of elements in the queue
public int size() {
return list.size();
}
//returns string representation of queue
public String toString() {
String result = "";
for(int i=front;i<rear;i++)
result+=list.get(i)+" ";
return result;
}
}
This is the driver class.
/*Demonstrates the use of a queue implemented by
* using a linked list*/
public class QueueLinkedListDemo {
public static void main(String[] args) {
Queue<Character> charList = new Queue<Character>();
//display size of queue
System.out.println("The size of the queue is " + charList.size());
//adding elements to queue
System.out.println("Calling enqueue() to add 'a' to the queue");
charList.enqueue('a');
System.out.println("Calling enqueue() to add 'b' to the queue");
charList.enqueue('b');
//display size of queue
System.out.println("The size of the queue is " + charList.size());
System.out.println("Calling dequeue() method to remove an element from the queue " + charList.dequeue());
System.out.println("Calling toString() method to display queue elements " + charList.toString());
//display first element of queue
System.out.println("The first element in queue is " + charList.first());
//display size of queue
System.out.println("The size of the queue is " + charList.size());
}
}
Output of this code: The size of the queue is 0 Calling enqueue() to add 'a' to the queue Calling enqueue() to add 'b' to the queue The size of the queue is 2 Calling dequeue() method to remove an element from the queue a Calling toString() method to display queue elements b The first element in queue is b The size of the queue is 2
Notice the size did not change from 2 to 1 when an element was removed from the queue. How can this be fixed?
size()
method return the size of the internal list, you probably meant to return thecount
variable instead ;) – litelite