-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMyQueue.java
82 lines (68 loc) · 1.22 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import java.util.*;
/*
Queue via Stacks: Implement a MyQueue class which implements a queue using two stacks.
*/
class MyStack {
int top;
List<Integer> arr;
MyStack() {
top = -1;
arr = new ArrayList<>();
}
boolean push(int x) {
arr.add(++top, x);
return true;
}
int pop() {
if (top == -1) {
throw new EmptyStackException();
}
return arr.remove(top--);
}
int peek() {
return arr.get(top);
}
int size() {
return top;
}
boolean isEmpty() {
return top == -1 ? true : false;
}
}
class MyQueue {
MyStack stack;
MyStack temp;
public MyQueue() {
stack = new MyStack();
temp = new MyStack();
}
public void push(int x) {
stack.push(x);
}
public int pop() {
if (stack.isEmpty()) {
throw new EmptyStackException();
}
while (stack.size() > 0) {
temp.push(stack.pop());
}
int x = stack.pop();
while (!temp.isEmpty()) {
stack.push(temp.pop());
}
return x;
}
public int peek() {
while (stack.size() > 0) {
temp.push(stack.pop());
}
int x = stack.peek();
while (!temp.isEmpty()) {
stack.push(temp.pop());
}
return x;
}
public boolean empty() {
return stack.isEmpty();
}
}