may31_21/Queue.java
may31_21/Queue.java
/* Created by IntelliJ IDEA.
* Author: Kshitij Varshney (kshitijvarshne1)
* Date: 29-May-21
* Time: 10:54 PM
* File: Queue.java
*/
package May.may31_21;
public class Queue {
private int maxQueueSize, front, rear, currentSize;
private int[] queue;
public Queue(int maxQueueSize) {
if (maxQueueSize <= 0)
System.out.println("Queue size should be a positive integer.");
else {
this.maxQueueSize = maxQueueSize;
front = rear = 0;
currentSize = 0;
queue = new int[maxQueueSize];
}
}
public void enqueue(int val) { // complete this method
if (rear == maxQueueSize && front != 0) {
int k = currentSize;
int a[] = new int[k];
int j = 0;
for (int i = front; i < rear; i++) {
a[j] = queue[i];
j += 1;
}
for (int i = 0; i < maxQueueSize; i++) {
queue[i] = -1;
}
for (int i = 0; i < k; i++) {
queue[i] = a[i];
}
front = 0;
rear = k;
queue[rear] = val;
currentSize += 1;
rear += 1;
} else if (rear == maxQueueSize) {
System.out.println("queue is full");
} else {
currentSize += 1;
queue[rear] = val;
rear += 1;
}
}
public int dequeue() { // complete this method
int k = -1;
if (rear > maxQueueSize) {
return k;
} else if (rear == front) {
k = queue[front];
rear = front = 0;
currentSize = 0;
} else {
k = queue[front];
front += 1;
currentSize -= 1;
}
return k;
}
public int size() { // complete this method
return currentSize;
}
public String toString() {
if (size() == 0)
return "[]";
else {
String output = "[";
if (rear > front) {
for (int i = front; i < rear - 1; i++)
output += queue[i] + ", ";
output += queue[rear - 1] + "]";
} else {
for (int i = front; i < maxQueueSize - 1; i++)
output += queue[i] + ", ";
output += queue[maxQueueSize - 1];
for (int i = 0; i < rear; i++)
output += ", " + queue[i];
output += "]";
}
return output;
}
}
}
/*
* if face any issue in any programming you can contact me at
[email protected] at any time
* */
may31_21/QueueUsingStack.java
may31_21/QueueUsingStack.java
/* Created by IntelliJ IDEA.
* Author: Kshitij Varshney (kshitijvarshne1)
* Date: 29-May-21
* Time: 11:07 PM
* File: QueueUsingStack.java
*/
package May.may31_21;
public class QueueUsingStack {
Stack mainStack;
int maxQueueSize;
int currentSize;
public QueueUsingStack(int maxQueueSize) {
this.maxQueueSize = maxQueueSize;
mainStack = new Stack(maxQueueSize);
this.currentSize = 0;
}
public void enqueue(int val) { // complete this method
if (currentSize < maxQueueSize) {
currentSize++;
mainStack.push(val);
} else {
System.out.println("queue full");
}
}
public int dequeue() { // complete this method
if (currentSize == 0) {
return -1;
}
int k...