Day 6:-
Program Statement:- A Tale of Two Stacks
On Paper:-
public static class MyQueue<T> {
Stack<T> stackNewestOnTop = new Stack<>();
Stack<T> stackOldestOnTop = new Stack<>();
public void enqueue(T value) { // Push onto newest stack
stackNewestOnTop.push(value);
}
public void dequeueOrPeek(int operation) {
if (stackOldestOnTop.isEmpty()) {
while (!stackNewestOnTop.isEmpty()) {
stackOldestOnTop.push(stackNewestOnTop.pop());
}
}
if (operation == 2)
stackOldestOnTop.pop();
else
System.out.println(stackOldestOnTop.peek());
}
}
public static void main(String[] args) {
MyQueue<Integer> queue = new MyQueue<>();
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
for (int i = 0; i < n; i++) {
int operation = scan.nextInt();
if (operation == 1) { // enqueue
queue.enqueue(scan.nextInt());
} else if (operation == 2 || operation == 3) { // dequeue
queue.dequeueOrPeek(operation);
}
}
scan.close();
}
Program Statement:- A Tale of Two Stacks
On Paper:-
public static class MyQueue<T> {
Stack<T> stackNewestOnTop = new Stack<>();
Stack<T> stackOldestOnTop = new Stack<>();
public void enqueue(T value) { // Push onto newest stack
stackNewestOnTop.push(value);
}
public void dequeueOrPeek(int operation) {
if (stackOldestOnTop.isEmpty()) {
while (!stackNewestOnTop.isEmpty()) {
stackOldestOnTop.push(stackNewestOnTop.pop());
}
}
if (operation == 2)
stackOldestOnTop.pop();
else
System.out.println(stackOldestOnTop.peek());
}
}
public static void main(String[] args) {
MyQueue<Integer> queue = new MyQueue<>();
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
for (int i = 0; i < n; i++) {
int operation = scan.nextInt();
if (operation == 1) { // enqueue
queue.enqueue(scan.nextInt());
} else if (operation == 2 || operation == 3) { // dequeue
queue.dequeueOrPeek(operation);
}
}
scan.close();
}
No comments:
Post a Comment