-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplement Stack Using Queue.cpp
More file actions
58 lines (51 loc) · 1.45 KB
/
Implement Stack Using Queue.cpp
File metadata and controls
58 lines (51 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Problem: Implement Stack using Queues
// LeetCode: https://leetcode.com/problems/implement-stack-using-queues/
//
// Approach:
// - We need to mimic **LIFO (stack)** behavior using a **queue (FIFO)**.
// - Idea: Always make the most recently pushed element appear at the **front** of the queue.
// • push(x):
// - Push element into queue.
// - Rotate the queue (size-1 times) so that x comes to the front.
// • pop():
// - Simply pop from front (which is the top of stack).
// • top():
// - Return the front element of queue.
// • empty():
// - Return whether queue is empty.
//
// Time Complexity:
// push: O(n) (because of rotation)
// pop, top, empty: O(1)
// Space Complexity: O(n)
class MyStack {
public:
queue<int> q; // single queue implementation
MyStack() {
// nothing to initialize
}
// Push element x onto stack
void push(int x) {
q.push(x);
int n = q.size();
// Rotate: move first (n-1) elements to back
for (int i = 0; i < n - 1; i++) {
q.push(q.front());
q.pop();
}
}
// Removes the element on top of the stack and returns it
int pop() {
int result = q.front();
q.pop();
return result;
}
// Get the top element
int top() {
return q.front();
}
// Returns whether the stack is empty
bool empty() {
return q.empty();
}
};