-
Notifications
You must be signed in to change notification settings - Fork 65
/
LinkedListBasedQueue.java
119 lines (105 loc) · 1.92 KB
/
LinkedListBasedQueue.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
111
112
113
114
115
116
117
118
119
/**
* Data-Structures-In-Java
* LinkedListBasedQueue.java
*/
package com.deepak.data.structures.Queue;
import java.util.NoSuchElementException;
/**
* Linked List based implementation of queue
*
* @author Deepak
*/
public class LinkedListBasedQueue {
/**
* Since in queue, we have to keep track of both the ends
* We need access to both head and tail node
*/
private Node head = null;
private Node tail = null;
/**
* Method to insert a item in the queue
*
* @param item
*/
public void enqueue(Object item) {
Node newNode = new Node(item, null);
if (isEmpty()) {
head = newNode;
} else {
tail.next = newNode;
}
tail = newNode;
}
/**
* Method to remove the item from the queue
*
* @return {@link object}
*/
public Object dequeue() {
if (isEmpty()) {
throw new NoSuchElementException("Cannot dequeue from empty Queue");
}
Object item = head.item;
if (tail == head) {
tail = null;
}
head = head.next;
return item;
}
/**
* Method to check the first item from the queue
*
* @return {@link object}
*/
public Object peek() {
if (head == null) {
throw new NoSuchElementException("Cannot peek from empty Queue");
}
return head.item;
}
/**
* Method to check the size of the queue
*
* @return {@link int}
*/
public int size() {
int count = 0;
for (Node node = head; node != null; node = node.next) {
count++;
}
return count;
}
/**
* Method to check if queue is empty
*
* @return {@link boolean}
*/
public boolean isEmpty() {
return head == null;
}
/**
* Node class for LinkedList based queue
*
* @author Deepak
*/
class Node {
/**
* Item in the node
*/
private Object item;
/**
* Pointer to next node
*/
private Node next;
/**
* Constructor to create a new node
*
* @param item
* @param next
*/
public Node(Object item, Node next) {
this.item = item;
this.next = next;
}
}
}