-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathQueueUsingStack.java
126 lines (107 loc) · 1.89 KB
/
QueueUsingStack.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
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package queue;
import java.util.*;
//O(N)
class QueueUS{
int rear;
Stack<Integer> s1;
Stack<Integer> s2;
QueueUS() {
s1 = new Stack<Integer>();
s2 = new Stack<Integer>();
}
void enqueue(int x) {
if(s1.size() == 0) {
s1.add(x);
} else {
while(s1.size()!=0) {
s2.add(s1.pop());
}
s1.add(x);
while(s2.size() != 0) {
s1.add(s2.pop());
}
}
rear = x;
}
int rear() {
if(s1.size() == 0) {
return -1;
}
return rear;
}
int dequeue() {
if(s1.size() == 0) {
return -1;
}
return s1.pop();
}
int front( ) {
if(s1.size() == 0) {
return -1;
}
return s1.peek();
}
boolean isEmpty() {
return s1.size() == 0;
}
}
//*Optimized approach* O(1) and amortised O(1)
class QueueOUS {
int rear;
Stack<Integer> input;
Stack<Integer> output;
QueueOUS() {
input = new Stack<>();
output = new Stack<>();
}
void enqueue(int x) {
input.add(x);
rear = x;
}
int dequeue() {
if(output.size() == 0) {
while(input.size()!=0) {
output.add(input.pop());
}
return output.pop();
}
return output.pop();
}
int front() {
if(output.size()==0) {
while(input.size() != 0) {
output.add(input.pop());
}
return output.peek();
}
return output.peek();
}
int rear() {
if(output.size() == 0) {
return -1;
}
return rear;
}
boolean isEmpty() {
return output.size() == 0;
}
}
public class QueueUsingStack {
public static void main(String[] args) {
QueueOUS q = new QueueOUS();
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
q.enqueue(4);
// System.out.println(q.front());
q.enqueue(5);
// System.out.println(q.dequeue());
q.enqueue(6);
System.out.println(q.dequeue());
q.enqueue(7);
while(!q.isEmpty()) {
System.out.println(q.dequeue());
}
System.out.println(q.rear());
}
}