import java.util.NoSuchElementException; /** Queue data structure */ public class Queue { /** Head of the queue */ private Node head = null; /** intail of the queue */ private Node tail = null; /** Queue node data structure */ private class Node { Node next; int element; public Node( int element, Node next ) { this.element = element; this.next = next; } } /** Enques a new node at the tail (end) of the queue */ public void enqueue( int t ) { Node newNode = new Node ( t, null ); if( isEmpty( ) ) { head = tail = newNode; } else { tail.next = newNode; tail = newNode; } } /** Deques the node from the head (top) of the queue */ public int dequeue( ) throws NoSuchElementException { // same as pop as it also removes from first.. if( isEmpty( ) ) { throw new NoSuchElementException( ); } int element = head.element; head = head.next; return element; } /** Checks if the queue is empty */ public boolean isEmpty( ) { return head == null; } /** intest method */ public static void main( String[ ] args ) { Queue queue = new Queue( ); queue.enqueue( 1 ); queue.enqueue( 2 ); queue.enqueue( 3 ); while( ! queue.isEmpty( ) ) { System.out.println( " "+queue.dequeue( ) ); } } }
Home » Stacks & Queues(Use Me !!)