-
Notifications
You must be signed in to change notification settings - Fork 0
/
QueueList.java
99 lines (83 loc) · 2.21 KB
/
QueueList.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
import java.util.*;
import java.lang.*;
/**
* This is the QueueList class.
* @author Wei Zhong Tee
* @since 8 May 2020
*/
public class QueueList<E> implements Queue<E> {
private Node<E> front; // Reference to front.
private Node<E> rear; //Reference to rear
private int size = 0;// Size of queue
/** Constructors **/
public QueueList(E it) {
front= rear = new Node<E>(it); // Create top that stores it
size++;
}
public QueueList() {
front = rear = null;//Create an empty front & rear
size = 0;
}
/** Returns true if the stack is empty; otherwise false
@return true is stack is empty otherwise false
*/
public boolean isEmpty() {
return size == 0;
}
/** Returns the object at the front of the queue without removing it
@return the object at the front of the queue
@throws NoSuchElementException
*/
public E front() {
if(isEmpty()) {
//System.out.println("Queue is empty");
throw new NoSuchElementException();
}
else {
return front.getElement();
}
}
/** Returns the object at the front of the queue and removes it
so stack is one smaller
@return the object at the front of the queue
@throws NoSuchElementException
*/
public E dequeue() {
if(isEmpty()) {
//System.out.println("Queue is empty");
throw new NoSuchElementException();
}
else {
E frontElement = front.getElement();
front = front.getNext();
size--;
return frontElement;
}
}
/** Pushes an item onto the rear of the queue
@param it The object to be inserted at the rear
*/
public void enqueue(E it) {
if (size == 0) {
front= rear = new Node<E>(it); // Create top that stores it
}
else {
Node<E> node = new Node <E> (it);
rear.setNext(node);
rear = node;
}
size ++;
}
/** Dumps the queue - clears it of its contents
*/
public void clear() {
front = rear = null;//Create an empty front & rear
size = 0;
}
/** Returns the number of elements in the queue
@return size - the number of elements on the queue
*/
public int size() {
return size;
}
}