Home » Stacks & Queues(Use Me !!)

Stacks & Queues(Use Me !!)


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( ) );
 }
 }
}

 


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Website

arpit tak

arpit tak

I like JAVA . I code. I chill. I blog.I eat. I sleep. I dream.

Personal Links

View Full Profile →

Followers

%d bloggers like this: