-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patha33stackUsingQueue.java
More file actions
44 lines (40 loc) · 1.18 KB
/
a33stackUsingQueue.java
File metadata and controls
44 lines (40 loc) · 1.18 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
import java.util.LinkedList;
import java.util.Queue;
public class a33stackUsingQueue {
Queue<Integer> queue1 = new LinkedList<>();
Queue<Integer> queue2 = new LinkedList<>();
public void push(int val) {
while (!queue1.isEmpty()){
queue2.offer(queue1.poll());
}
queue1.offer(val);
while (!queue2.isEmpty()){
queue1.offer(queue2.poll());
}
}
public int peek() {
if(queue1.isEmpty()){
System.out.println("Stack is empty");
return -1;
}
return queue1.peek();
}
public int pop() {
if(queue1.isEmpty()){
System.out.println("Stack is empty");
return -1;
}
return queue1.poll();
}
public static void main(String[] args) {
a33stackUsingQueue stack = new a33stackUsingQueue();
stack.push(10);
System.out.println( stack.peek()); // 10
stack.push(20);
stack.push(30);
stack.push(40);
System.out.println(stack.peek()); // 40
System.out.println(stack.pop()); // 40
System.out.println(stack.peek()); // 30
}
}