8000 implement_queue_using_stacks · hitzzc/go-leetcode@c45380a · GitHub
[go: up one dir, main page]

Skip to content

Commit c45380a

Browse files
committed
implement_queue_using_stacks
1 parent da618fa commit c45380a

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
188188
#### [229. Majority Element II](https://github.com/hitzzc/go-leetcode/tree/master/majority_element_II)
189189
#### [230. Kth Smallest Element in a BST](https://github.com/hitzzc/go-leetcode/tree/master/kth_smallest_element_in_a_BST)
190190
#### [231. Power of Two](https://github.com/hitzzc/go-leetcode/tree/master/power_of_two)
191+
#### [232. Implement Queue using Stacks](https://github.com/hitzzc/go-leetcode/tree/master/implement_queue_using_stacks)
191192

192193

193194

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
#include <stack>
2+
using namespace std;
3+
4+
class Queue {
5+
public:
6+
stack<int> push_stack;
7+
stack<int> pop_stack;
8+
// Push element x to the back of queue.
9+
void push(int x) {
10+
push_stack.push(x);
11+
}
12+
13+
// Removes the element from in front of queue.
14+
void pop(void) {
15+
if (pop_stack.empty()){
16+
while (!push_stack.empty()) {
17+
pop_stack.push(push_stack.top());
18+
push_stack.pop();
19+
}
20+
}
21+
pop_stack.pop();
22+
}
23+
24+
// Get the front element.
25+
int peek(void) {
26+
if (pop_stack.empty()){
27+
while (!push_stack.empty()) {
28+
pop_stack.push(push_stack.top());
29+
push_stack.pop();
30+
}
31+
}
32+
return pop_stack.top();
33+
}
34+
35+
// Return whether the queue is empty.
36+
bool empty(void) {
37+
return pop_stack.empty() && push_stack.empty();
38+
}
39+
};

0 commit comments

Comments
 (0)
0