Skip to content

Commit ac29292

Browse files
Bruce YangBruce Yang
Bruce Yang
authored and
Bruce Yang
committed
Add C++ solution for leetcode 232.
1 parent 3bdc66b commit ac29292

2 files changed

+132
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
#include<stack>
2+
#include<algorithm>
3+
#include<iostream>
4+
using namespace std;
5+
6+
class MyQueue {
7+
stack<int> s1, s2;
8+
int front;
9+
10+
public:
11+
/** Initialize your data structure here. */
12+
MyQueue() {}
13+
14+
/** Push element x to the back of queue. */
15+
void push(int x) {
16+
if (s1.empty())
17+
front = x;
18+
19+
s1.push(x);
20+
}
21+
22+
/** Removes the element from in front of queue and returns that element. */
23+
int pop() {
24+
if (s2.empty())
25+
{
26+
while (!s1.empty())
27+
{ /* 把s1中的元素全部移到s2中 */
28+
s2.push(s1.top());
29+
s1.pop();
30+
}
31+
}
32+
int res = s2.top();
33+
s2.pop();
34+
35+
return res;
36+
}
37+
38+
/** Get the front element. */
39+
int peek() {
40+
if (!s2.empty())
41+
return s2.top();
42+
43+
return front;
44+
}
45+
46+
/** Returns whether the queue is empty. */
47+
bool empty() {
48+
return s1.empty() && s2.empty();
49+
}
50+
};
51+
52+
// Test
53+
int main()
54+
{
55+
MyQueue* q = new MyQueue();
56+
q->push(1);
57+
q->push(2);
58+
int val = q->peek();
59+
cout << val << endl;
60+
int val2 = q->pop(); // return 1, queue is [2]
61+
cout << val2 << endl;
62+
bool isEmpty = q->empty();
63+
cout << (isEmpty ? "true" : "false") << endl;
64+
65+
return 0;
66+
}
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
#include<stack>
2+
#include<algorithm>
3+
#include<iostream>
4+
using namespace std;
5+
6+
class MyQueue {
7+
stack<int> s1, s2;
8+
int front;
9+
10+
public:
11+
/** Initialize your data structure here. */
12+
MyQueue() {}
13+
14+
/** Push element x to the back of queue. */
15+
void push(int x) {
16+
if (s1.empty())
17+
front = x;
18+
19+
s1.push(x);
20+
}
21+
22+
/** Removes the element from in front of queue and returns that element. */
23+
int pop() {
24+
if (s2.empty())
25+
{
26+
while (!s1.empty())
27+
{ /* 把s1中的元素全部移到s2中 */
28+
s2.push(s1.top());
29+
s1.pop();
30+
}
31+
}
32+
int res = s2.top();
33+
s2.pop();
34+
35+
return res;
36+
}
37+
38+
/** Get the front element. */
39+
int peek() {
40+
if (!s2.empty())
41+
return s2.top();
42+
43+
return front;
44+
}
45+
46+
/** Returns whether the queue is empty. */
47+
bool empty() {
48+
return s1.empty() && s2.empty();
49+
}
50+
};
51+
52+
// Test
53+
int main()
54+
{
55+
MyQueue* q = new MyQueue();
56+
q->push(1);
57+
q->push(2);
58+
int val = q->peek();
59+
cout << val << endl;
60+
int val2 = q->pop(); // return 1, queue is [2]
61+
cout << val2 << endl;
62+
bool isEmpty = q->empty();
63+
cout << (isEmpty ? "true" : "false") << endl;
64+
65+
return 0;
66+
}

0 commit comments

Comments
 (0)