The simplest example of a queue is the typical line that we all participate in from time to time. We wait in a line for a movie, we wait in the check-out line at a grocery store, and we wait in the cafeteria line (so that we can pop the tray stack). Well-behaved lines, or queues, are very restrictive in that they have only one way in and only one way out. There is no jumping in the middle and no leaving before you have waited the necessary amount of time to get to the front.
Basic Queue Operations
Following code represents the implementation of a generic Queue.
public class Queue<T> {
private class Node {
private T data;
private Node next;
}
private Node first;
private Node last;
private int size;
public Queue() {
this.first = null;
this.last = null;
this.size = 0;
}
}
Enqueue
public Queue<T> enqueue(T data) {
if (data == null) {
return this;
}
Node current = last;
last = new Node();
last.data = data;
if (size == 0) {
first = last;
} else {
current.next = last;
}
size++;
return this;
}
Dequeue
public T dequeue() {
if (size == 0) {
return null;
}
T value = first.data;
first = first.next;
if (--size == 0) {
last = null;
}
return value;
}
public boolean isEmpty() {
return this.size == 0;
}
Source Code
public class Queue<T> {
private class Node {
private T data;
private Node next;
}
private Node first;
private Node last;
private int size;
public Queue() {
this.first = null;
this.last = null;
this.size = 0;
}
public Queue<T> enqueue(T data) {
if (data == null) {
return this;
}
Node current = last;
last = new Node();
last.data = data;
if (size == 0) {
first = last;
} else {
current.next = last;
}
size++;
return this;
}
public T dequeue() {
if (size == 0) {
return null;
}
T value = first.data;
first = first.next;
if (--size == 0) {
last = null;
}
return value;
}
public boolean isEmpty() {
return this.size == 0;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
Node tmp = first;
while (tmp != null) {
sb.append(tmp.data).append(", ");
tmp = tmp.next;
}
return sb.toString();
}
}
JUnit Test
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class QueueAPITest {
@Test
public void testEnqueue() {
Queue<String> queueAPI = new Queue<String>();
queueAPI.enqueue("n1");
queueAPI.enqueue("n2");
queueAPI.enqueue("n3");
queueAPI.enqueue("n4");
queueAPI.enqueue("n5");
System.out.println(queueAPI.toString());
}
@Test
public void testDequeue() {
Queue<String> queueAPI = new Queue<String>();
queueAPI.enqueue("n1");
queueAPI.enqueue("n2");
queueAPI.enqueue("n3");
queueAPI.enqueue("n4");
queueAPI.enqueue("n5");
assertTrue("n1".equals(queueAPI.dequeue()));
assertTrue("n2".equals(queueAPI.dequeue()));
assertFalse("n6".equals(queueAPI.dequeue()));
}
}
References
Queue on WikipediaQueue on Interactive Python
No comments:
Post a Comment