forked from super30admin/Design-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MyQueue.java
67 lines (56 loc) · 1.35 KB
/
MyQueue.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
// Time Complexity : O(1) amortized
// Space Complexity : O(n)
// Did this code successfully run on Leetcode : Yes
import java.util.Stack;
public class MyQueue {
Stack<Integer> inStack;
Stack<Integer> outStack;
public MyQueue()
{
this.inStack = new Stack<>();
this.outStack = new Stack<>();
}
public void push(int value) // pushing elements inside the stack
{
inStack.push(value);
}
public int pop()
{
if(empty())
return -1;
peek();
return outStack.pop();
}
public int peek()
{
if(empty())
return -1;
if(outStack.isEmpty())
{
while(!inStack.isEmpty())
{
outStack.push(inStack.pop());//push elements from inStack to outStack to pop the first element inserted.
}
}
return outStack.peek();
}
public boolean empty()
{
return outStack.isEmpty() && inStack.isEmpty();
}
public static void main(String[] args) {
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
System.out.println(myQueue);
System.out.println(myQueue.peek());
System.out.println(myQueue.pop());
System.out.println(myQueue.empty());
myQueue.pop();
myQueue.pop();
myQueue.pop();
// return 1
//.pop(); // return 1, queue is [2]
//myQueue.empty(); // return false
}
}