-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patha32queueUsingStack.java
More file actions
85 lines (77 loc) · 2.25 KB
/
a32queueUsingStack.java
File metadata and controls
85 lines (77 loc) · 2.25 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
import java.util.Queue;
import java.util.Stack;
public class a32queueUsingStack {
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
// 1st method
// public void enqueue(int val) {
// stack1.push(val);
// }
// public int dequeue(){
// if(stack1.isEmpty()){
// System.out.println("Stack is Empty");
// return -1;
// }
// while(!stack1.isEmpty()){
// stack2.push(stack1.pop());
// }
// int val = stack2.pop();
// while(!stack2.isEmpty()){
// stack1.push(stack2.pop());
// }
// return val;
// }
//
// public int peek(){
// if(stack1.isEmpty()){
// System.out.println("Stack is Empty");
// return -1;
// }
// while(!stack1.isEmpty()){
// stack2.push(stack1.pop());
// }
// int val = stack2.peek();
// while(!stack2.isEmpty()){
// stack1.push(stack2.pop());
// }
// return val;
// }
// 2nd method
public void enqueue(int val) {
// move all elements from stack 1 to stack 2
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
// insert value in stack 1
stack1.push(val);
// move all elements from stack 2 to stack 1
while(!stack2.isEmpty()){
stack1.push(stack2.pop());
}
}
public int dequeue(){
if(stack1.isEmpty()){
System.out.println("Queue is Empty");
return -1;
}
return stack1.pop();
}
public int peek(){
if(stack1.isEmpty()){
System.out.println("Stack is Empty");
return -1;
}
return stack1.peek();
}
public static void main(String[] args) {
// Queue<Integer> queue = new LinkedList<>();
a32queueUsingStack queue = new a32queueUsingStack();
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
System.out.println("Peek is " + queue.peek());
System.out.println("DEQUEUE is " + queue.dequeue());
queue.enqueue(7);
System.out.println("Peek is " + queue.peek());
}
}