Skip to content

Commit 013151f

Browse files
author
Li Li
committed
modified code of 225
1 parent 597c907 commit 013151f

File tree

1 file changed

+7
-16
lines changed

1 file changed

+7
-16
lines changed

Algorithms Basics/Chapter 4. Stack and Queue/225. Implement Stack using Queues.cs

Lines changed: 7 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,24 @@
11
public class MyStack {
2-
/** q1 only keeps last items, q2 keeps others. */
32
private Queue<int> q1;
4-
private Queue<int> q2;
53

64
/** Initialize your data structure here. */
75
public MyStack() {
86
q1 = new Queue<int>();
9-
q2 = new Queue<int>();
107
}
118

129
/** Push element x onto stack. */
1310
public void Push(int x) {
14-
// Empty q1 for push
15-
while (q1.Count > 0) {
16-
q2.Enqueue(q1.Dequeue());
17-
}
1811
q1.Enqueue(x);
12+
int size = q1.Count;
13+
while (size-- > 1) {
14+
int temp = q1.Dequeue();
15+
q1.Enqueue(temp);
16+
}
1917
}
2018

2119
/** Removes the element on top of the stack and returns that element. */
2220
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();
3122
return top;
3223
}
3324

@@ -38,7 +29,7 @@ public int Top() {
3829

3930
/** Returns whether the stack is empty. */
4031
public bool Empty() {
41-
return q1.Count == 0 && q2.Count == 0;
32+
return q1.Count == 0;
4233
}
4334
}
4435

0 commit comments

Comments
 (0)