forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedQueue.java
88 lines (76 loc) · 1.81 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
package com.rampatra.base;
import java.util.NoSuchElementException;
/**
* Queue implementation using a singly linked list with two pointers.
*
* @author rampatra
* @since 4/12/15
*/
public class LinkedQueue<E> implements Queue<E> {
Node<E> front;
Node<E> rear;
public LinkedQueue() {
front = null;
rear = null;
}
@Override
public E add(E item) {
if (front == null || rear == null) {
front = rear = new Node<>(item, null);
} else {
rear.next = new Node<>(item, null);
rear = rear.next;
}
return item;
}
@Override
public E remove() {
if (front == null) {
throw new NoSuchElementException();
}
E item = element();
front = front.next;
return item;
}
@Override
public E element() {
if (front == null) {
throw new NoSuchElementException();
}
return front.item;
}
@Override
public int size() {
int count = 0;
if (front == null) return count;
for (Node node = front; node != rear; node = node.next) {
count++;
}
return count;
}
@Override
public boolean isEmpty() {
return front == null;
}
@Override
public void print() {
Node<E> node;
System.out.print("[");
if (front == null) {
System.out.println("]");
return;
}
for (node = front; node != rear; node = node.next) {
System.out.print(node.item + ",");
}
System.out.println(node.item + "]");
}
private class Node<E> {
E item;
Node<E> next;
public Node(E item, Node<E> next) {
this.item = item;
this.next = next;
}
}
}