File tree Expand file tree Collapse file tree 1 file changed +7
-16
lines changed
Algorithms Basics/Chapter 4. Stack and Queue Expand file tree Collapse file tree 1 file changed +7
-16
lines changed Original file line number Diff line number Diff line change 1
1
public class MyStack {
2
- /** q1 only keeps last items, q2 keeps others. */
3
2
private Queue < int > q1 ;
4
- private Queue < int > q2 ;
5
3
6
4
/** Initialize your data structure here. */
7
5
public MyStack ( ) {
8
6
q1 = new Queue < int > ( ) ;
9
- q2 = new Queue < int > ( ) ;
10
7
}
11
8
12
9
/** Push element x onto stack. */
13
10
public void Push ( int x ) {
14
- // Empty q1 for push
15
- while ( q1 . Count > 0 ) {
16
- q2 . Enqueue ( q1 . Dequeue ( ) ) ;
17
- }
18
11
q1 . Enqueue ( x ) ;
12
+ int size = q1 . Count ;
13
+ while ( size -- > 1 ) {
14
+ int temp = q1 . Dequeue ( ) ;
15
+ q1 . Enqueue ( temp ) ;
16
+ }
19
17
}
20
18
21
19
/** Removes the element on top of the stack and returns that element. */
22
20
public int Pop ( ) {
23
- int top = q1 . Dequeue ( ) ; // hold this top one until finish prepare new q1;
24
- // swap q1 and q2. move all items (but remain one for next time pop) from new q1 to q2
25
- var temp = q1 ;
26
- q1 = q2 ;
27
- q2 = temp ;
28
- while ( q1 . Count > 1 ) {
29
- q2 . Enqueue ( q1 . Dequeue ( ) ) ;
30
- }
21
+ int top = q1 . Dequeue ( ) ;
31
22
return top ;
32
23
}
33
24
@@ -38,7 +29,7 @@ public int Top() {
38
29
39
30
/** Returns whether the stack is empty. */
40
31
public bool Empty ( ) {
41
- return q1 . Count == 0 && q2 . Count == 0 ;
32
+ return q1 . Count == 0 ;
42
33
}
43
34
}
44
35
You can’t perform that action at this time.
0 commit comments