Skip to content

Instantly share code, notes, and snippets.

@pedrofurtado
Created January 3, 2016 16:16
Show Gist options
  • Save pedrofurtado/099feeebb64c2816ad91 to your computer and use it in GitHub Desktop.
Save pedrofurtado/099feeebb64c2816ad91 to your computer and use it in GitHub Desktop.
Implementation of Queue data structure in Java
/**
* @file
* Queue.
*
* Implementation with singly linked list, through the nested class QueueNode.
* It's used nested class to improve encapsulation.
*
* @author Pedro Furtado
*/
public class Queue {
/**
* Properties of queue.
*/
private QueueNode begin = null;
private QueueNode end = null;
/**
* Element of queue.
*/
class QueueNode {
public int key;
public QueueNode next = null;
QueueNode(int key) {
this.key = key;
}
}
/**
* Default constructor method.
*/
Queue() {
}
/**
* Overloading of Queue() constructor method.
*
* Allow to add to queue a single key on instantiation of the queue.
*
* @param int key
* Integer key.
*/
Queue(int key) {
this.queue(key);
}
/**
* Overloading of Queue() constructor method.
*
* Allow to add to queue a list of keys on instantiation of the queue.
*
* @param int[] keys
* List of integer keys.
*/
Queue(int[] keys) {
for (int key : keys) {
this.queue(key);
}
}
/**
* Enqueue method.
*
* Add an element to the end of the queue.
*
* @param int key
* Integer key.
* @return void
*/
public void queue(int key) {
QueueNode node = new QueueNode(key);
if (this.is_empty()) {
this.begin = node;
}
else {
this.end.next = node;
}
this.end = node;
}
/**
* Dequeue method.
*
* Remove an element from the beginning of the queue.
*
* @return int
* Queue element or -5 if is empty.
*/
public int dequeue() {
if (this.is_empty()) return -5;
int key = this.begin.key;
if (this.begin == this.end) {
this.end = null;
}
this.begin = this.begin.next;
return key;
}
/**
* Size method.
*
* Determines the size of queue, i.e., the number of elements in queue.
*
* @return int
* Number of elements in queue.
*/
public int size() {
QueueNode p = this.begin;
int i = 0;
while(p != null) {
i++;
p = p.next;
}
return i;
}
/**
* Empty method.
*
* Determines if the queue is empty, i.e., if it does not have elements inside.
*
* @return boolean
*/
public boolean is_empty() {
return this.begin == null;
}
/**
* toString method.
*
* Provide some visual funcionality to see the elements inside the queue.
*
* @return String
* Representation of the queue in the moment by a string.
*/
public String toString() {
if (this.is_empty()) return "Empty queue.";
QueueNode p = this.begin;
String description = "Queue: ";
while(p != null) {
description += p.key + " ";
p = p.next;
}
return description;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment