Implementing a Simple FIFO Queue in Java Using Linked List

First In First Out (FIFO) queues can be easily implemented in Java using a singly linked list. This example shows a very simple implementation of the queue operations using singly linked list.

package com.icodejava.published.datastructure;
/**
 * 
 * @author Kushal Paudyal
 * Created on: 2/8/2017
 * Last Modified on: 2/8/2017
 *
 * This class shows a simple implementation of Queue using LinkedList
 */
import java.util.LinkedList;

public class QueueUsingLinkedList {

	private LinkedList<Object> data = new LinkedList<Object>();

	public void enqueue(Object item) {
		data.addLast(item);
		System.out.println("Added: " + item);
	}

	public Object dequeue() {
		System.out.println("Removed: " + data.getFirst());
		return data.removeFirst();
		
	}

	public Object peek() {
		return data.getFirst();
	}

	public int size() {
		return data.size();
	}

	public boolean isEmpty() {
		return data.isEmpty();
	}
	
	/**
	 * Testing the stack. The added objects should be returned in same order
	 */
	public static void main (String args[]) {
		QueueUsingLinkedList queue = new QueueUsingLinkedList();
		System.out.println("===ENQUEUE===");
		queue.enqueue("One");
		queue.enqueue("Two");
		queue.enqueue("Three");
		
		System.out.println("\n===DEQUEUE===");
		while (!queue.isEmpty()) {
			queue.dequeue();
		}
	}
}

Here is the output of running the above program:

===ENQUEUE===
Added: One
Added: Two
Added: Three

===DEQUEUE===
Removed: One
Removed: Two
Removed: Three

  1. Implementing a Simple LIFO Stack in Java using LinkedList
  2. Implementing a Simple FIFO Queue in Java Using Linked List
  3. In Place Matrix (2D Array) Clockwise and Counterclockwise Rotation – Java Implementation
  4. Matrix (2D Array) Clockwise and Counterclockwise Rotation with Extra Buffer – Java Implementation
  5. Array Max Integer Finder (With Big O Analysis)
  6. A Basic Implementation of Binary Tree in Java
  7. A Basic Implementation of Generic Tree in Java
  8. Basic example of implementing Singly Linked List in Java
  9. How to Add and Remove nodes in an unsorted Linked List
  10. Rotating a two dimensional integer array In-Place and using extra memory
  11. How to reverse a Singly Linked List iteratively and recursively
  12. Sorted Circular Linked List Implementation And Insert Operation
  13. Finding Mean Value Of An Integer Array In Java
  14. How to intersect two sets in Java using java.util.Set data structure.
  15. Bubble Sorting An Integer Array In Ascending and Descending Order
  16. How to split strings and separate the words with spaces
  17. How to easily sort characters in a String?
Tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *