File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed
Algorithms Basics/Chapter 4. Stack and Queue Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ // use two stack.
2
+ public class MyQueue {
3
+ private Stack < int > s1 ;
4
+ private Stack < int > s2 ;
5
+ private int front ;
6
+ /** Initialize your data structure here. */
7
+ public MyQueue ( ) {
8
+ s1 = new Stack < int > ( ) ;
9
+ s2 = new Stack < int > ( ) ;
10
+ }
11
+
12
+ /** Push element x to the back of queue. */
13
+ public void Push ( int x ) {
14
+ if ( s1 . Count == 0 ) {
15
+ front = x ;
16
+ }
17
+ s1 . Push ( x ) ;
18
+ }
19
+
20
+ /** Removes the element from in front of queue and returns that element. */
21
+ public int Pop ( ) {
22
+ if ( s2 . Count == 0 ) {
23
+ while ( s1 . Count > 0 ) {
24
+ s2 . Push ( s1 . Pop ( ) ) ;
25
+ }
26
+ }
27
+ return s2 . Pop ( ) ;
28
+ }
29
+
30
+ /** Get the front element. */
31
+ public int Peek ( ) {
32
+ if ( s2 . Count == 0 ) {
33
+ return front ;
34
+ }
35
+ return s2 . Peek ( ) ;
36
+ }
37
+
38
+ /** Returns whether the queue is empty. */
39
+ public bool Empty ( ) {
40
+ return s1 . Count == 0 && s2 . Count == 0 ;
41
+ }
42
+ }
43
+
44
+ /**
45
+ * Your MyQueue object will be instantiated and called as such:
46
+ * MyQueue obj = new MyQueue();
47
+ * obj.Push(x);
48
+ * int param_2 = obj.Pop();
49
+ * int param_3 = obj.Peek();
50
+ * bool param_4 = obj.Empty();
51
+ */
You can’t perform that action at this time.
0 commit comments