In: Computer Science
Implement the \void enqueue(int val)" function in the QueueUsingStack.java/QueueUsingStack.h file (ATTACHED BELOW). Here are some hints on how to implement this using two stacks:
- Create a stack \tempStack", which has the same maximum capacity as the mainStack.
- Pop all numbers from mainStack and push them onto tempStack.
- Push the new number onto mainStack.
- Pop all numbers from tempStack and push them onto mainStack.
Implement the \int dequeue()" function in the
QueueUsingStack.java/QueueUsingStack.h le. Recall that this is
nothing but a pop on the mainStack.
Implement the \int getSize()" function in the
QueueUsingStack.java/QueueUsingStack.h le. Recall that this is
nothing but the size of mainStack.
public class QueueUsingStack {
Stack mainStack;
int maxQueueSize;
public QueueUsingStack(int maxQueueSize) {
this.maxQueueSize = maxQueueSize;
mainStack = new Stack(maxQueueSize);
}
public void enqueue(int val) { // complete this function
}
public int dequeue() { // complete this function
}
public int getSize() { // complete this function
}
public String toString() {
if (getSize() == 0) {
return "[]";
} else {
String output = "[";
int n = getSize();
for (int i = 0; i < n - 1; i++) {
int x = dequeue();
output += x + ", ";
enqueue(x);
}
int x = dequeue();
output += x + "]";
enqueue(x);
return output;
}
}
}
import java.util.Stack;
public class QueueUsingStack {
Stack mainStack;
Stack s2;
int maxQueueSize;
public QueueUsingStack(int maxQueueSize) {
this.maxQueueSize = maxQueueSize;
mainStack = new Stack();
s2 = new Stack();
}
public void enqueue(int val) { // complete this function
while (!mainStack.isEmpty()) {
s2.push(mainStack.pop());
}
mainStack.push(val);
while (!s2.isEmpty()) {
mainStack.push(s2.pop());
}
}
public int dequeue() { // complete this function
if (mainStack.isEmpty()) {
System.out.println("Queue is Empty");
return -1;
}
int answer = (int) mainStack.peek();
mainStack.pop();
return answer;
}
public int getSize() { // complete this function
return mainStack.size();
}
public String toString() {
if (getSize() == 0) {
return "[]";
} else {
String output = "[";
int n = getSize();
for (int i = 0; i < n - 1; i++) {
int x = dequeue();
output += x + ", ";
enqueue(x);
}
int x = dequeue();
output += x + "]";
enqueue(x);
return output;
}
}
}