Reversing queue with array java - java

Hello I was trying to figure out how to reverse a queue with the use of an array. Ive attached the queue class and a the runner class which created the queue and adds the elements inside of it. The reverse method I have creates an array and my thought would be to check the elements remove and add it to the array created. Im new to queue and an a little lost. Thanks for any help an advanced.
public class Queue{
private int QUEUE_SIZE = 5;
private Object[] items;
private int front, back, count;
public Queue() {
items = new Object[QUEUE_SIZE];
front = 0;
back = QUEUE_SIZE -1;
count =0;
}
public boolean isEmpty(){
return count==0;
}
public boolean isFull(){
return count == QUEUE_SIZE;
}
public void enqueue(Object newItem){
if (!isFull()){
back = (back+1) % QUEUE_SIZE;
items[back] = newItem;
count++;
return;
} else
System.out.println(
"Trying to enqueue into a full queue");
}
public Object dequeue(){
if (!isEmpty()){
Object queueFront = items[front];
front = (front+1) % QUEUE_SIZE;
count--;
return queueFront;
}else
System.out.println(
"Trying to dequeue from an empty queue");
return null;
}
public void dequeueAll(){
items = new Object[QUEUE_SIZE];
front = 0;
back = QUEUE_SIZE -1;
count =0;
}
public Object peek(){
if (!isEmpty()) {
return items[front];
}
else
System.out.println(
"Trying to peek with empty queue");
return null;
}
public int size(){
return count;
}
}
// queue created with reverse method
public class RunnerQueue {
public static void main(String args[]){
Queue q = new Queue();
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
q.enqueue(40);
q.enqueue(50);
public static void reverseQueue(Queue Q){
int[] revQue = new int(Q.size);
While(!Q.isEmpty()){
}
}
}

I think you have the right idea so far. Assuming all of your queue methods work, such as size, enqueue, dequeue, etc., then all you have do is as you dequeue elements off of the queue one by one, insert those elements from the end of the array towards the start. You can have a counter that keeps track of where you want to insert the element in the array. This counter would start at Q.size() - 1 since queues follow the FIFO, first-in-first-out principle. Then, with the help of a helper method, you can set the items variable in your queue to revQue after you've populated the elements of the array with the items of the original queue in reverse order. For example, you could modify your reverseQueue method to look something like this,
public static void reverseQueue(Queue Q){
int[] revQue = new int[Q.size()];
int i = Q.size() - 1;
while(!Q.isEmpty()){
revQue[i] = Q.dequeue();
i--;
}
Q.setItems(revQue);
}
And this is what the setItems method would look like, added to your Queue class,
public void setItems(Object[] items) {
this.items = items;
this.QUEUE_SIZE = items.length;
this.front = 0;
this.back = items.length - 1;
this.count = items.length;
}
Just a note that the setItems method here assumes perfect circumstances, meaning that the items parameter passed in has a valid element at each spot within the array. For the reverseQueue method, this should work assuming that your other queue methods work as intended. But keep in mind that the setItems method can cause problems if you pass in an array with gaps in it; for example, null elements at certain indices.

Here's the update class:
public class Queue
{
private int QUEUE_SIZE = 5;
private Object[] items;
private int front, back, count;
public Queue() {
items = new Object[QUEUE_SIZE];
front = 0;
back = QUEUE_SIZE -1;
count =0;
}
public boolean isEmpty(){
return count==0;
}
public boolean isFull(){
return count == QUEUE_SIZE;
}
public void enqueue(Object newItem){
if (!isFull()){
back = (back+1) % QUEUE_SIZE;
items[back] = newItem;
count++;
return;
} else
System.out.println(
"Trying to enqueue into a full queue");
}
public Object dequeue(){
if (!isEmpty()){
Object queueFront = items[front];
front = (front+1) % QUEUE_SIZE;
count--;
return queueFront;
}else
System.out.println(
"Trying to dequeue from an empty queue");
return null;
}
public void dequeueAll(){
items = new Object[QUEUE_SIZE];
front = 0;
back = QUEUE_SIZE -1;
count =0;
}
public Object peek(){
if (!isEmpty()) {
return items[front];
}
else
System.out.println(
"Trying to peek with empty queue");
return null;
}
public int size(){
return count;
}
public static void reverseQueue(Queue q)
{
if(q.isEmpty())
{
return;
}
Object data = q.peek();
q.dequeue();
reverseQueue(q);
q.enqueue(data);
}
public static void printQueue(Queue q)
{
while(!q.isEmpty())
{
System.out.println(q.dequeue());
}
}
public static void main(String[] args)
{
Queue q = new Queue();
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
q.enqueue(40);
q.enqueue(50);
reverseQueue(q);
printQueue(q);
}
}
So the idea is pop the element from the queue, if it has elements. Call the reverseQueue method for the remaining values in the queue, then put the values that were removed from the queue back onto it. Making it in the reverse order.

Related

why is my queue size always zero? it should increse when insert is called

hi I have to take a list of commands as Strings such as "INSERT ONE" or "REMOVE" and apply them to a queue and I have to write my own Queue class after the commands have gone through the size of the queue is always zero and I need to use the queue size later
here is my Queue class
package cs210;
public class Queue
{
private int maxSize;
private String[] queArray;
private int front;
private int rear;
private int nItems;
//constructor
public Queue(int s)
{
maxSize = s;
queArray = new String[maxSize];
front = 0;
rear = -1;
nItems = 0;
}
//insert method to add to the rear of the queue
public boolean insert(String j)
{
if(isFull())
return false; //Can't add if full
if(rear == maxSize-1)
rear = -1; //wrap around
rear++; // Increase rear
queArray[rear] = j; //Insert value
nItems++;//item number increased
return true; // Insert successful
}
//remove method takes item from the front of the queue
public String remove()
{
if(isEmpty())
return null; //Don't remove if empty
String temp = queArray[front]; //get value and increase front
front++;
if(front == maxSize)
front = 0; //wrap around
nItems--; //item number decreased
return temp;
}
//peek method see the value at the front of the queue
public String peekFront()
{
return queArray[front];
}
//check is queue empty(true)
public boolean isEmpty()
{
return (nItems == 0);
}
//check is queue full(true)
public boolean isFull()
{
return (nItems == maxSize);
}
//number of items in the queue
public int size()
{
return nItems;
}
}
and here is my main class
package cs210;
import java.util.Scanner;
public class labquestion
{
public static void main(String arg[])
{
Scanner s = new Scanner(System.in);
int queuesize = s.nextInt();
Queue Q = new Queue(queuesize);
s.nextLine();
for (int i = 0; i < queuesize;i++)
{
String[] command = s.nextLine().split(" ");
switch (command[0])
{
case"INSERT":
Q.insert(command[1]);
case"REMOVE":
Q.remove();
break;
}
}
s.close();
System.out.println(Q.size());
System.out.println(Q.peekFront());
}
Your case for inserting isn't followed by a break statement:
case "INSERT":
Q.insert(command[1]);
case "REMOVE":
Q.remove();
break;
Switch cases by design "fall through" without a break statement. Meaning they will continue executing the lines of code until they hit a break; statement or the end of the switch statement.
So in your case when you insert an element it will also always execute the code for
case "REMOVE":
So every time you insert something in your Queue you immediately remove from it as well, which will mean the size will always stay 0.
To fix it simply add a break after your insert case:
case "INSERT":
Q.insert(command[1]);
break;
case "REMOVE":
Q.remove();
break;

thread.main problem with my java interface queue, how to solve it?

I working on my homework assignment, build code to queue with support of interface, I wrote my code but the output hade main.thread issue, to be honest I could not find the issue,however I do believe the issue is from insertion,mainly in the size increment, I appreciate some advice
public class MyQueue implements IntQueue {
private int[] heltal;
private int size;
public void enqueue(int tal) {
// Inserts the specified element into the end of this queue.
// increases the size after every insertion
if (size == 0) {
size++;
heltal[0] = tal;
int[] newArr = new int[heltal.length * 2];
for (int i = 0; i < heltal.length; i++) {
newArr[i] = heltal[i];
}
heltal = newArr;
}
return;
}
public int dequeue() throws NoSuchElementException {
// Returns the head of this queue and removes it.
// Throws an exception if this queue is empty.
if (empty())
throw new NoSuchElementException("The queue is empty");
int NewValue = heltal[0];
for (int i = 1; i < size; i++) {
heltal[i - 1] = heltal[i];
}
heltal[size - 1] = 0;
size--;
return NewValue;
}
#Override
public int peek() throws NoSuchElementException {
// Retrieves, but does not remove, the head of this queue.
// Throws an exception if this queue is empty.
if (empty())
throw new NoSuchElementException("The queue is empty");
return heltal[0];
}
#Override
public boolean empty() {
// Checks if this queue is empty.
return size == 0;
}
}
Initialize your array like below
private int[] heltal = new int[100];
and see if it works

How is this java code is deleting an item from a list without using .remove()?

I'm reading an algorithms textbook and I came across this line from a code example:
long temp = queArray[front++];
I understand what the front++ is doing and what item it is accessing, but this seems to be also deleting the item from the array. I don't understand how it is doing that.
In case I missed something, here is the rest of the method:
public long remove() { // take item from front of queue
long temp = queArray[front++]; // get value and incr front
if(front == maxSize) // deal with wraparound
front = 0;
nItems--; // one less item
return temp;
}
Additionally, here is the rest of the class:
class Queue
{
private int maxSize;
private long[] queArray;
private int front;
private int rear;
private int nItems;
public Queue(int s) // constructor
{
maxSize = s;
queArray = new long[maxSize];
front = 0;
rear = -1;
nItems = 0;
}
public void insert(long j) // put item at rear of queue
{
if(rear == maxSize-1) // deal with wraparound
rear = -1;
queArray[++rear] = j; // increment rear and insert
nItems++; // one more item
}
public long remove() // take item from front of queue
{
long temp = queArray[front++]; // get value and incr front
if(front == maxSize) // deal with wraparound
front = 0;
nItems--; // one less item
return temp;
}
public long peekFront() // peek at front of queue
{
return queArray[front];
}
public boolean isEmpty() // true if queue is empty
{
return (nItems==0);
}
public boolean isFull() // true if queue is full
{
return (nItems==maxSize);
}
public int size() // number of items in queue
{
return nItems;
}
} // end class Queue

using Java Loop for ArrayList to print each time

I have a method which I basically want to simulate first filling the queue and then after that removing the first person and adding a new person each time in my public void mySimulation() method:
import java.util.*;
public class People {
private final int DEFAULT_CAPACITY = 100;
private int front, rear, count;
private ArrayList<thePeople> people;
private int theMaxCapacity;
//-----------------------------------------------------------------
// Creates an empty queue using the specified capacity.
//-----------------------------------------------------------------
public People(int initialCapacity) {
front = rear = count = 0;
people = new ArrayList<thePeople>(Collections.nCopies(5, (thePeople) null));
}
//-----------------------------------------------------------------
// Adds the specified element to the rear of the queue, expanding
// the capacity of the queue array if necessary.
//-----------------------------------------------------------------
public void enque(thePeople element) {
if (this.isFull()) {
System.out.println("Queue Full");
System.exit(1);
} else {
people.set(rear, element);
rear = rear + 1;
if (rear == people.size()) {
rear = 0;
}
count++;
}
}
//-----------------------------------------------------------------
// Removes the element at the front of the queue and returns a
// reference to it. Throws an EmptyCollectionException if the
// queue is empty.
//-----------------------------------------------------------------
public thePeople dequeue() {
if (isEmpty()) {
System.out.println("Empty Queue");
}
thePeople result = people.get(front);
people.set(front, null);
front = (front + 1) % people.size();
count--;
return result;
}
//-----------------------------------------------------------------
// Returns true if this queue is empty and false otherwise.
//-----------------------------------------------------------------
public boolean isEmpty() {
return (count == 0);
}
//-----------------------------------------------------------------
// Returns the number of elements currently in this queue.
//-----------------------------------------------------------------
public int size() {
return count;
}
public boolean isFull() {
return count == people.size();
}
public void mySimulation() {
Random rand1 = new Random();
thePeople theM = null;
if (this.isFull()) {
this.people.remove(0);
System.out.println("Enqueueing...");
this.enque(people.get(rand1.nextInt(people.size())));
thePeople r1 = people.get(rear - 1);
System.out.println(people.toString());
System.out.println(r1);
for (int e = 0; e < people.size(); e++) {
if (people.get(e) instanceof thePeople) {
System.out.println("G");
} else {
System.out.println("D");
}
}
}
}
//-----------------------------------------------------------------
// Returns a string representation of this queue.
//-----------------------------------------------------------------
#Override
public String toString() {
String result = "";
int scan = 0;
while (scan < count) {
if (people.get(scan) != null) {
result += people.get(scan).toString() + "\n";
}
scan++;
}
return result;
}
public static void main(String[] args) {
People Q1 = new People(25);
thePeople call1 = new thePeople("John King", "001 456 789");
thePeople call2 = new thePeople("Michael Fish", "789 654 321");
Q1.enque(call1);
Q1.enque(call2);
System.out.println(Q1.toString());
ArrayList<thePeople> callerDetails = new ArrayList<>(Arrays.asList(call1, call2));
Random rand = new Random();
for (int z = 0; z <= 4; z++) {
Q1.enque(callerDetails.get(rand.nextInt(callerDetails.size())));
}
System.out.println(Q1.toString());
}
}
any suggestions on how I could repeat this process such that I will first check that the queue is full,
if so remove the first item and add a new person to it using my arrayList each time i my my public void mySimulation() method: as I cant get my head round this at the moment?
Your code is filled with errors:
First make sure you remove the "the" you accidently placed before people in many lines of your code .
Then adjust some of your methods to the right parameters and return types.
As for you question:
it is simple
public void MySimulation(){
if(Queue.isFull()){
Queue.dequeue;}
Queue.enqueue;}

Queue array implementation resize

I was required to create a simple queue array implementation with basic methods as enqueue, dequeue, isEmpty, and stuff like that. My only problem is that Im stuck when it comes to the resize method, because if I want to add more values to my queue (with fixed size because is an array) I do not know how to make it work and keep all the values in place.
Everything works just in case you were wondering, the only thing is that doesnt work is my resize (the method wrote in here wasn't the only one I tried).
I'm going to put my main method as well if you want to try it, hope you can help, thanks.
Main Method:
public class MainQueue {
public static void main(String[] args) {
int capacity=10;
Queue<Integer> queue = new Queue<Integer>(capacity);
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.enqueue(4);
queue.enqueue(5);
queue.enqueue(6);
queue.enqueue(7);
queue.enqueue(8);
queue.enqueue(9);
queue.enqueue(10);
System.out.println("Queue: "+ queue);
//WORKS SO FAR
queue.enqueue(11);
//11 is placed at the beginning of the queue
//instead at the end and my last value is null (?)
Class queue:
import java.util.NoSuchElementException;
public class Queue <E>{
private E[] elements;//array in generic
private int front;//first element or front of the queue
private int back;//last element or back of the queue
private int capacity; //capacity of the queue
private int count; //indicates number of elements currently stored in the queue
#SuppressWarnings("unchecked")
public Queue(int size)
{
capacity = size;
count = 0;
back = size-1;
front = 0;
elements =(E []) new Object[size]; //array empty
}
//Returns true if the queue is empty or false
public boolean isEmpty()
{
return count==0;//means its true
}
//Add elements to the queue
public void enqueue(E item)
{
if(count == capacity)
{
resize(capacity*2);
// System.out.println("Queue is full");
}
back =(back+1) % capacity; //example back=(0+1)%10=1
elements[back]=item;
//elements[0]=0
//item=elements[count];
count++;
}
//Public resize
public void resize(int reSize){
E[] tmp = (E[]) new Object[reSize];
int current = front;
for (int i = 0; i < count; i++)
{
tmp[i] = elements[current];
current = (current + 1) % count;
}
elements = tmp;
}
//Dequeue method to remove head
public E dequeue()
{
if(isEmpty())
throw new NoSuchElementException("Dequeue: Queue is empty");
else
{
count--;
for(int x = 1; x <= count; x++)
{
elements[x-1] = elements[x];
}
capacity--;
return (E) elements;
}
}
//peek the first element
public E peek()
{
if(isEmpty())
{
throw new NoSuchElementException("Peek: Queue is empty");
}
else
return elements[front];
}
//Print queue as string
public String toString()
{
if(isEmpty()) {
System.out.println("Queue is empty.");
//throw new NoSuchElementException("Queue is empty");
}
String s = "[";
for(int i = 0; i <count; i++)
{
if(i != 0)
s += ", ";
s = s + elements[i];// [value1,value2,....]
}
s +="]";
return s;
}
public void delete() { //Delete everything
count = 0;
}
}
you forgot to update stuff when resizing:
front, capacity and back .
public void resize(int reSize){
E[] tmp = (E[]) new Object[reSize];
int current = front;
for (int i = 0; i < count; i++)
{
tmp[i] = elements[current];
current = (current + 1) % count;
}
elements = tmp;
front = 0;
back = count-1;
capacity=reSize;
}
You have few mistakes in resizing when enqueing item which expand queue.
in resize algorithm
current = (current + 1) % count; should be (current + 1) % capacity
You have to change capacity value in resize function
capacity = resize;
Why are you changing capacity when dequeing?

Categories

Resources