forked from coder2hacker/Explore-open-source
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueueUsingTwoStacks.java
More file actions
67 lines (55 loc) · 1.35 KB
/
QueueUsingTwoStacks.java
File metadata and controls
67 lines (55 loc) · 1.35 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
package com.company;
import java.util.Stack;
public class QueueUsingTwoStacks {
static class MyQueue{
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
public boolean isEmpty(){
return stack1.isEmpty();
}
//0(N)
public void add(int data){
if (isEmpty()){
stack1.push(data);
}
else {
while (!isEmpty()){
stack2.push(stack1.peek());
stack1.pop();
}
stack1.push(data);
while (!stack2.isEmpty()){
stack1.push(stack2.peek());
stack2.pop();
}
}
}
//0(1)
public void remove(){
if (isEmpty()){
System.out.println(-1);
}
else {
stack1.pop();
}
}
public int peek(){
if (isEmpty()){
return -1;
}
return stack1.peek();
}
}
public static void main(String[] args) {
MyQueue queue = new MyQueue();
queue.add(1);
queue.add(2);
queue.add(3);
queue.remove();
queue.add(4);
while (!queue.isEmpty()){
System.out.println(queue.peek());
queue.remove();
}
}
}