forked from noodles-sed/Simple-DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplement_Queue_as_Stack.cpp
More file actions
62 lines (53 loc) · 1.39 KB
/
Copy pathImplement_Queue_as_Stack.cpp
File metadata and controls
62 lines (53 loc) · 1.39 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
59
60
61
62
// Implement Queue using Stacks
// LeetCode 232
// Time Complexity: Amortized O(1) per operation
// Space Complexity: O(n)
#include <stack>
using namespace std;
class MyQueue {
stack<int> inStack; // Used for enqueue operations
stack<int> outStack; // Used for dequeue and peek operations
public:
// Constructor
MyQueue() {}
// Push element x to the back of queue.
void enqueue(int x) {
inStack.push(x);
}
// Helper function to transfer elements if outStack is empty
void transfer() {
if (outStack.empty()) {
while (!inStack.empty()) {
outStack.push(inStack.top());
inStack.pop();
}
}
}
// Removes the element from the front of the queue and returns it.
int dequeue() {
transfer();
int front = outStack.top();
outStack.pop();
return front;
}
// Get the front element.
int peek() {
transfer();
return outStack.top();
}
// Returns true if the queue is empty, false otherwise.
bool empty() {
return inStack.empty() && outStack.empty();
}
};
// Example usage
#include <iostream>
int main() {
MyQueue q;
q.enqueue(1);
q.enqueue(2);
cout << q.peek() << endl; // Output: 1
cout << q.dequeue() << endl; // Output: 1
cout << q.empty() << endl; // Output: 0 (false)
return 0;
}