-
Notifications
You must be signed in to change notification settings - Fork 65
/
StackBasedQueue.java
110 lines (98 loc) · 1.86 KB
/
StackBasedQueue.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
/**
* Data-Structures-In-Java
* StackBasedQueue.java
*/
package com.deepak.data.structures.Queue;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Stack;
/**
* Implement a queue based on the stack
*
* @author Deepak
*
* @param <T>
*/
public class StackBasedQueue<T> {
/* Two stacks for the implementation */
private Stack<T> stack1 = null;
private Stack<T> stack2 = null;
/**
* Default Constructor
*/
public StackBasedQueue() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
/**
* Method to peek from the queue
*
* @return {@link T}
*/
public T peek() {
if (isEmpty()) {
throw new NoSuchElementException("Stack Underflow!!");
}
if (stack2.isEmpty()) {
moveStack1ToStack2();
}
return stack2.peek();
}
/**
* Method to enqueue a element
*
* @param item
*/
public void enqueue(T item) {
stack1.push(item);
}
/**
* Method to dequeue an element
*
* @return {@link T}
*/
public T dequeue() {
if (isEmpty()) {
throw new NoSuchElementException("Stack Underflow!!");
}
if (stack2.isEmpty()) {
moveStack1ToStack2();
}
return stack2.pop();
}
/**
* Method to display elements from the queue
*/
public void display() {
if (!stack1.isEmpty()) {
System.out.println(Arrays.toString(stack1.toArray()));
}
if (!stack2.isEmpty()) {
System.out.println(Arrays.toString(stack2.toArray()));
}
}
/**
* Method to return size of the queue
*
* @return {@link int}
*/
public int size() {
return stack1.size() + stack2.size();
}
/**
* Method to check if queue is empty
*
* @return {@link boolean}
*/
public boolean isEmpty() {
return stack1.isEmpty() && stack2.isEmpty();
}
/**
* Method to move elements from stack 1 to stack 2
*/
private void moveStack1ToStack2() {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
}