Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 601
Expand file tree
/
Copy pathImplementQueueusingStacks.java
More file actions
Latest commit
109 lines (89 loc) · 2.46 KB
/
Copy pathImplementQueueusingStacks.java
File metadata and controls
109 lines (89 loc) · 2.46 KB
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
packageproblems.easy;
importjava.util.Stack;
/**
* Created by sherxon on 2016-12-29.
*/
publicclassImplementQueueusingStacks {
staticclassMyQueue {
Stack<Integer> stack;
Stack<Integer> helper;
Integerpeek = null;
/**
* Initialize your data structure here.
*/
publicMyQueue() {
stack = newStack<>();
helper = newStack<>();
}
/**
* Push element x to the back of queue.
*/
publicvoidpush(intx) {
stack.push(x);
if (peek == null) peek = x;
}
/**
* Removes the element from in front of queue and returns that element.
*/
publicintpop() {
helper.clear();
while (!stack.isEmpty())
helper.push(stack.pop());
intx = helper.pop();
if (!helper.isEmpty())
peek = helper.peek();
elsepeek = null;
while (!helper.isEmpty())
stack.push(helper.pop());
returnx;
}
/**
* Get the front element.
*/
publicintpeek() {
returnpeek;
}
/**
* Returns whether the queue is empty.
*/
publicbooleanempty() {
returnstack.isEmpty();
}
}
/**
* This is the second optimized solution with
* */
publicclassMyQueue2 {
Stack<Integer> stack;
Stack<Integer> helper;
/** Initialize your data structure here. */
publicMyQueue2() {
stack= newStack<>();
helper= newStack<>();
}
/** Push element x to the back of queue. */
publicvoidpush(intx) {
stack.push(x);
}
/** Removes the element from in front of queue and returns that element. */
publicintpop() {
if(helper.isEmpty()){
while(!stack.isEmpty())
helper.push(stack.pop());
}
returnhelper.pop();
}
/** Get the front element. */
publicintpeek() {
if(helper.isEmpty()){
while(!stack.isEmpty())
helper.push(stack.pop());
}
returnhelper.peek();
}
/** Returns whether the queue is empty. */
publicbooleanempty() {
returnhelper.isEmpty() && stack.isEmpty();
}
}
}