We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Queue using Two Stacks
Queue using Two Stacks
Sort by
recency
|
519 Discussions
|
Please Login in order to post a comment
My solution:
If, despite properly adhering to the specifications, the test cases are timing out, one viable solution would be to stack stacks - push items to a buffer stack and then utilize the submitted queue solution to hold filled stacks. It certainly interprets the requirements in a lenient way, but relies on stacks only; and if you interpret the buffer stack as not counting toward the overall stack limit then it suits them perfectly. ;)
Really using two stacks:
java solution
import java.io.; import java.util.;
public class Solution {
}
Approach: * take 2 stacks one for enque and another for deque. * if operation is enqueue simply push to first stack * if operation is dequeue - check if there are elements in 2nd stack if not copy all elements from 1st stack and pop the top. Otherwise simply pop 2nd stack top * if operation is front - follow above step instead of popping print the top.
Gist is: stack 2 will have a top element to pop or print. We only copy stack 1 elements into stack 2 when it is empty.