Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Completed Design-2 [2024] Problem4 #2029

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions 2024_Problem4_Impl_Queue_using_Stack.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
//232. Implement Queue using Stacks - https://leetcode.com/problems/implement-queue-using-stacks/description/
//Time Complexity: All operation takes constant time O(1)
//Space Complexity: O(n)

class MyQueue {

Stack<Integer> stack;
Stack<Integer> reverseStack;

public MyQueue() {
this.stack = new Stack<>();
this.reverseStack = new Stack<>();
}

public void push(int x) {
stack.push(x); // Push element x to the end
}

private void reverseStack(){
while(!stack.empty()){
reverseStack.push(stack.pop()); //pop elements from main stack and push in reverseStack in reverse order
}
}

/** Removes the element from in front of queue and returns that element. */
public int pop() {
int popElement = -1; //default value of stack if empty

if(reverseStack.empty())
reverseStack(); //populate the reverse stack

popElement = reverseStack.pop(); //poping the first element in queue
return popElement;
}

/** Get the front element. */
public int peek() {
int peekElement = -1; //default value if stack is empty

if(reverseStack.empty())
reverseStack(); //populate the reverse stack

peekElement = reverseStack.peek(); //peeking the first element in queue w/o poping
return peekElement;
}

/** Returns whether the queue is empty. */
public boolean empty() {
return (stack.empty() && reverseStack.empty());
}
}
Empty file.