-
-
Notifications
You must be signed in to change notification settings - Fork 610
/
ImplementQueueusingStacks.java
109 lines (89 loc) · 2.46 KB
/
ImplementQueueusingStacks.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package problems.easy;
import java.util.Stack;
/**
* Created by sherxon on 2016-12-29.
*/
public class ImplementQueueusingStacks {
static class MyQueue {
Stack<Integer> stack;
Stack<Integer> helper;
Integer peek = null;
/**
* Initialize your data structure here.
*/
public MyQueue() {
stack = new Stack<>();
helper = new Stack<>();
}
/**
* Push element x to the back of queue.
*/
public void push(int x) {
stack.push(x);
if (peek == null) peek = x;
}
/**
* Removes the element from in front of queue and returns that element.
*/
public int pop() {
helper.clear();
while (!stack.isEmpty())
helper.push(stack.pop());
int x = helper.pop();
if (!helper.isEmpty())
peek = helper.peek();
else peek = null;
while (!helper.isEmpty())
stack.push(helper.pop());
return x;
}
/**
* Get the front element.
*/
public int peek() {
return peek;
}
/**
* Returns whether the queue is empty.
*/
public boolean empty() {
return stack.isEmpty();
}
}
/**
* This is the second optimized solution with
* */
public class MyQueue2 {
Stack<Integer> stack;
Stack<Integer> helper;
/** Initialize your data structure here. */
public MyQueue2() {
stack= new Stack<>();
helper= new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
stack.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(helper.isEmpty()){
while(!stack.isEmpty())
helper.push(stack.pop());
}
return helper.pop();
}
/** Get the front element. */
public int peek() {
if(helper.isEmpty()){
while(!stack.isEmpty())
helper.push(stack.pop());
}
return helper.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return helper.isEmpty() && stack.isEmpty();
}
}
}