-
Notifications
You must be signed in to change notification settings - Fork 69
/
QueueUsingStacks.java
79 lines (59 loc) Β· 1.92 KB
/
QueueUsingStacks.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
package hacktoberfest;
import java.util.*;
public class QueueUsingStacks {
Stack<Integer> input; // For pushing elements
Stack<Integer> output; // For popping and peeking elements
// Constructor to initialize the Stacks
public QueueUsingStacks() {
input = new Stack<>();
output = new Stack<>();
}
// Method to push element x to the end of queue
public void push(int x) {
System.out.println(x + " is pushed!");
input.push(x);
}
// Method to pop the element from the front and return it
public int pop() {
// Swap input and output stacks
if (output.empty()) {
while (input.empty() == false) {
output.push(input.peek());
input.pop();
}
}
int x = output.peek();
output.pop();
return x;
}
// Get the front element of the queue
public int peek() {
// Swap input and output stacks
if (output.empty())
while (input.empty() == false) {
output.push(input.peek());
input.pop();
}
return output.peek();
}
// Method to get the total size of the queue
public int size() {
return (output.size() + input.size());
}
// Driver Code
public static void main(String args[]) {
QueueUsingStacks ob = new QueueUsingStacks();
// Push operation
ob.push(4);
ob.push(16);
ob.push(25);
ob.push(36);
System.out.println();
// Pop operation
System.out.println(ob.pop() + " was popped!\n");
// Peek operation
System.out.println("Top element is " + ob.peek() + "\n");
// Get total size of the queue
System.out.println("Total size of the queue is " + ob.size());
}
}