-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedQueue.java
104 lines (90 loc) · 2.22 KB
/
LinkedQueue.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
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Ragha
*/
public class LinkedQueue<T> {
private Node<T> front; // Reference to front queue node
private Node<T> last; // Reference to last queue node
private int size; // Number of elements in queue
/**
* Constructors
*/
public LinkedQueue() {
front = last = null;
size = 0;
}
public LinkedQueue(Node node) {
front = last = node;
size = 0;
}
/**
* @return Queue size
*/
public int length() {
return size;
}
/**
* Clear
*/
public void clear() {
front = last = null;
size = 0;
}
/**
* Put element on last
*/
public void enqueue(T data) {
Node<T> temp = new Node<T>(data, null);
if (size == 0) {
front = last = temp;
} else {
last = last.next = temp;
}
size++;
}
/**
* Remove and return element from front
*/
public T dequeue() {
if (size == 0) {
System.out.println("Queue is empty");
return null;
}
T data = front.data; // Store dequeued value
front = front.next; // Advance front
if (front == null) {
last = front; // Last Object
}
size--;
return data; // Return Object
}
/**
* @return Front data
*/
public T frontValue() {
if (size == 0) {
System.out.println("Queue is empty");
return null;
}
return front.data;
}
boolean isEmpty() {
return size == 0;
}
boolean contains(T dataNode) {
if(isEmpty())
return false;
Node<T> current = front;
while(current != null){
if(current.data.equals(dataNode))
return true;
current = current.next;
}
return false;
}
}