File tree Expand file tree Collapse file tree 3 files changed +42
-0
lines changed
implement-queue-using-stacks Expand file tree Collapse file tree 3 files changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ class MyQueue {
2
+
3
+ // should use Deque<Integer> stack in modern java
4
+ Stack <Integer > stack = new Stack <>();
5
+
6
+ // Push element x to the back of queue.
7
+ public void push (int x ) {
8
+ Stack <Integer > rev = new Stack <>();
9
+
10
+ while (!stack .empty ()){
11
+ rev .push (stack .pop ());
12
+ }
13
+
14
+ rev .push (x );
15
+
16
+ while (!rev .empty ()){
17
+ stack .push (rev .pop ());
18
+ }
19
+ }
20
+
21
+ // Removes the element from in front of queue.
22
+ public void pop () {
23
+ stack .pop ();
24
+ }
25
+
26
+ // Get the front element.
27
+ public int peek () {
28
+ return stack .peek ();
29
+ }
30
+
31
+ // Return whether the queue is empty.
32
+ public boolean empty () {
33
+ return stack .empty ();
34
+ }
35
+ }
Original file line number Diff line number Diff line change
1
+ ---
2
+ layout : solution
3
+ title : Implement Queue using Stacks
4
+ date : 2015-07-07 21:04:46+08:00
5
+ leetcode_id : 232
6
+ ---
7
+ {% include_relative README.md %}
You can’t perform that action at this time.
0 commit comments