forked from super30admin/Design-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyQueue.java
More file actions
90 lines (70 loc) · 1.93 KB
/
MyQueue.java
File metadata and controls
90 lines (70 loc) · 1.93 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
/*
Time Complexity:
PUSH : O(1)
POP : O(1) average case but in worst case O(n)
Peek : O(1)
Space Complexity :
Used two Stack each hold N input size:
that's why space complexty is O(N)
Tested in Leetcode Successfully : YES
Challenges face : It was easy no trouble
*/
import java.util.Deque;
import java.util.Stack;
class MyQueue {
Stack<Integer> stack;
Stack<Integer> stack1;
int front ;
/** Initialize your data structure here. */
public MyQueue() {
stack = new Stack<>();
stack1 = new Stack<>();
front = Integer.MAX_VALUE;
}
/** Push element x to the back of queue. */
public void push(int x) {
if(stack.isEmpty()){
front = x;
}
stack.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(stack1.isEmpty()){
while(!stack.isEmpty()){
stack1.push(stack.pop());
}
}
int remove = stack1.pop();
return remove;
}
/** Get the front element. */
public int peek() {
if (!stack1.isEmpty()){
return stack1.peek();
}
else{
return front;
}
}
/** Returns whether the queue is empty. */
public boolean empty() {
return stack.isEmpty() && stack1.isEmpty();
}
public static void main(String[] args) {
// Your MyQueue object will be instantiated and called as such:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
// queue.push(4);
System.out.println(queue.pop());
queue.push(3);
queue.push(4);
System.out.println(queue.pop());
System.out.println(queue.peek());
System.out.println();
// while(!queue.empty()){
// System.out.println(queue.pop());
// }
}
}