mirror of
https://github.com/arkorty/LeetCode.git
synced 2026-03-18 00:57:17 +00:00
Initial commit
This commit is contained in:
43
Easy/implement-queue-using-stacks/solution.cpp
Normal file
43
Easy/implement-queue-using-stacks/solution.cpp
Normal file
@@ -0,0 +1,43 @@
|
||||
#include <stack>
|
||||
|
||||
class MyQueue {
|
||||
private:
|
||||
std::stack<int> shelfA;
|
||||
std::stack<int> shelfB;
|
||||
|
||||
public:
|
||||
MyQueue() {}
|
||||
|
||||
void push(int data) { shelfA.push(data); }
|
||||
|
||||
int pop() {
|
||||
while (shelfA.size() != 1) {
|
||||
shelfB.push(shelfA.top());
|
||||
shelfA.pop();
|
||||
}
|
||||
int result = shelfA.top();
|
||||
shelfA.pop();
|
||||
while (!shelfB.empty()) {
|
||||
shelfA.push(shelfB.top());
|
||||
shelfB.pop();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
int peek() {
|
||||
while (shelfA.size() != 1) {
|
||||
shelfB.push(shelfA.top());
|
||||
shelfA.pop();
|
||||
}
|
||||
int result = shelfA.top();
|
||||
while (!shelfB.empty()) {
|
||||
shelfA.push(shelfB.top());
|
||||
shelfB.pop();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
bool empty() { return shelfA.empty(); }
|
||||
};
|
||||
Reference in New Issue
Block a user