Implement Queue using Stacks
class MyQueue() { private val enqueueStack: MutableList<Int> = mutableListOf() private val dequeueStack: MutableList<Int> = mutableListOf() fun enqueue(x: Int): Unit { enqueueStack.add(x) } fun dequeue(): Int { if (dequeueStack.isEmpty()) { if (enqueueStack.isEmpty()) { throw NoS...
This implementation simulates a queue data structure using two stacks. A queue follows the First-In, First-Out (FIFO) principle, while stacks follow Last-In, First-Out (LIFO). This approach is a classic exercise in under...
The `MyQueue` class uses two stacks: `enqueueStack` and `dequeueStack`. When an element is enqueued, it's simply pushed onto `enqueueStack`. When `dequeue` or `peek` is called, if `dequeueStack` is empty, all elements from `enqueueStack` are popped and pushed onto `dequeueStack`. This reverses the order, making the oldest element accessible at the top of `dequeueStack`. The `empty` method checks if both stacks are empty. The amortized time complexity for `enqueue` is O(1). The amortized time complexity for `dequeue` and `peek` is O(1) because each element is moved from `enqueueStack` to `dequeueStack` at most once. In the worst case, a single `dequeue` or `peek` operation could be O(n) if all elements need to be transferred. The space complexity is O(n) to store the elements.
class MyQueue: initialize enqueueStack as empty stack initialize dequeueStack as empty stack method enqueue(x): push x onto enqueueStack method dequeue(): if dequeueStack is empty: if enqueueStack is empty: throw error "...