File tree 1 file changed +21
-46
lines changed
scripts/algorithms/I/Implement Stack using Queues
1 file changed +21
-46
lines changed Original file line number Diff line number Diff line change 1
- // Runtime: 8 ms (Top 6.60%) | Memory: 7 MB (Top 20.63%)
1
+ // Runtime: 3 ms (Top 41.4%) | Memory: 7.10 MB (Top 85.79%)
2
+
2
3
class MyStack {
3
4
public:
5
+ /* * Initialize your data structure here. */
4
6
queue<int > q1;
5
- queue<int > q2;
6
7
MyStack () {
7
-
8
+
8
9
}
9
-
10
+
11
+ /* * Push element x onto stack. */
10
12
void push (int x) {
13
+ int sz = q1.size ();
11
14
q1.push (x);
12
- }
13
-
14
- int pop () {
15
-
16
- while (q1.size () !=1 ){
17
- int temp = q1.front ();
15
+ while (sz--){
16
+ q1.push (q1.front ());
18
17
q1.pop ();
19
- q2.push (temp);
20
18
}
21
- int temp = q1.front ();
19
+ }
20
+
21
+ /* * Removes the element on top of the stack and returns that element. */
22
+ int pop () {
23
+ int result = top ();
22
24
q1.pop ();
23
- while (!q2.empty ()){
24
- int tp = q2.front ();
25
- q2.pop ();
26
- q1.push (tp);
27
- }
28
- return temp;
25
+ return result;
29
26
}
30
-
27
+
28
+ /* * Get the top element. */
31
29
int top () {
32
- while (q1.size () !=1 ){
33
- int temp = q1.front ();
34
- q1.pop ();
35
- q2.push (temp);
36
- }
37
- int temp = q1.front ();
38
- q1.pop ();
39
- q2.push (temp);
40
- while (!q2.empty ()){
41
- int tp = q2.front ();
42
- q2.pop ();
43
- q1.push (tp);
44
- }
45
- return temp;
30
+ return q1.front ();
46
31
}
47
-
32
+
33
+ /* * Returns whether the stack is empty. */
48
34
bool empty () {
49
- if (q1.empty ()){
50
- return true ;
51
- }
52
- return false ;
35
+ return q1.empty ();
53
36
}
54
37
};
55
38
56
- /* *
57
- * Your MyStack object will be instantiated and called as such:
58
- * MyStack* obj = new MyStack();
59
- * obj->push(x);
60
- * int param_2 = obj->pop();
61
- * int param_3 = obj->top();
62
- * bool param_4 = obj->empty();
63
- */
You can’t perform that action at this time.
0 commit comments