File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed
implement-queue-using-stacks Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change 1+
2+ class MyQueue {
3+ public:
4+ stack<int > temp, ans;
5+ /* * Initialize your data structure here. */
6+ MyQueue () {
7+
8+ }
9+
10+ /* * Push element x to the back of queue. */
11+ void push (int x) {
12+ temp.push (x);
13+ }
14+
15+ /* * Removes the element from in front of queue and returns that element. */
16+ int pop () {
17+ // shift input to output
18+ if (ans.empty ())
19+ while (temp.size ())
20+ ans.push (temp.top ()), temp.pop ();
21+
22+ int x = ans.top ();
23+ ans.pop ();
24+ return x;
25+ }
26+
27+ /* * Get the front element. */
28+ int peek () {
29+ // shift input to output
30+ if (ans.empty ())
31+ while (temp.size ())
32+ ans.push (temp.top ()), temp.pop ();
33+ return ans.top ();
34+ }
35+
36+ /* * Returns whether the queue is empty. */
37+ bool empty () {
38+ return temp.empty () && ans.empty ();
39+ }
40+
41+ };
You can’t perform that action at this time.
0 commit comments