-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyQueue.java
More file actions
96 lines (80 loc) · 1.8 KB
/
MyQueue.java
File metadata and controls
96 lines (80 loc) · 1.8 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
import java.util.*;
// // LINKED LIST
// class Node {
// int val;
// Node next;
// public Node(int val) {
// this.val = val;
// this.next = null;
// }
// }
// public class MyQueue {
// int size;
// Node start;
// Node end;
// public MyQueue() {
// this.size = 0;
// this.start = null;
// this.end = null;
// }
// public void push(int x) {
// Node node = new Node(x);
// if(start == null) {
// start = node;
// end = node;
// }
// else {
// end.next = node;
// end = end.next;
// size++;
// }
// }
// public int pop() {
// if(start == null) return -1;
// Node temp = start;
// start = start.next;
// size--;
// return temp.val;
// }
// public int top() {
// if(start == null) return -1;
// return start.val;
// }
// public int size() {
// return size;
// }
// }
// STACK
public class MyQueue {
Stack<Integer> s1;
Stack<Integer> s2;
public MyQueue() {
this.s1 = new Stack<>();
this.s2 = new Stack<>();
}
public void push(int x) {
s1.push(x);
}
public int pop() {
if(!s2.isEmpty()) {
return s2.pop();
}
else {
while(!s1.isEmpty()) {
s2.push(s1.pop());
}
return s2.pop();
}
}
public int top() {
if(!s2.isEmpty()) {
return s2.peek();
}
else {
while(!s1.isEmpty()) {
s2.push(s1.pop());
}
return s2.peek();
}
}
}