Advertisement
cr34tiv3

[JAVA]Queue Class

Nov 12th, 2012
30
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.29 KB | None | 0 0
  1. import java.util.*; public class Queue{    int size = 0;    node front, rear = null;         public boolean isEmpty()    {        return (front == null); //If true, front points to null    }          public void enqueue(String input) //Adds a value to the rear of the queue    {        node n = new node();        n.string = input;   //Takes passed in value and stores in variable string of object n        n.next = null;                  if (isEmpty() == true)             front = n; //If empty, points front to object n        else                rear = n; //Points rear to newly created node                         size++; //Increments when value added to queue    }             public String dequeue() //Takes value from end of queue, removes it and displays it    {           String s = null;        node temp; //Creates pointer temp pointed to the removed node                 if (isEmpty() == true) //Checks to see if queue is empty            System.out.println("Queue is empty.");        else        {            temp = front; //Copies the head pointer into temp            s = temp.string; //Copies the value in the last node of the queue to s            front = temp.next; //Make rear point to next node on the list            temp = null; //Delete the object temp, nulling object allows garbage collector to delete object                         size--; //Decrements ever time a value is dequeued        }           return s;           }         public String first() //Takes value from front of the queue and displays it without removing it    {               String s = null;        node temp; //Creates pointer temp                  if (isEmpty() == true)            System.out.println("Queue is empty.");        else        {            temp = front; //Copies the head pointer into temp            s = temp.string; //Copies the value in the top node of the queue to s        }                 return s; //Returns the value in s    }         public int size() //Method to determine the size of the queue    {        return size;    }             public String toString()    {        System.out.println("The queue from first to last contains: ");                 for (node n = front; n != null; n = n.next) //Loop to access each node and print string        {            System.out.println(n.string);        }        return null;    }}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement