Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package QueueClassPractice;
- /**
- *
- * @author acer
- */
- public class ListQueue {
- Node f;
- Node r;
- int size;
- public ListQueue(){
- f=null;
- r=null;
- size=0;
- }
- // The number of items in the queue
- public int size(){
- return size;
- }
- // Returns true if the queue is empty
- public boolean isEmpty(){
- if(f==null)
- return true;
- return false;
- }
- // Adds the new item on the back of the queue, throwing the
- // QueueOverflowException if the queue is at maximum capacity. It
- // does not throw an exception for an "unbounded" queue, which
- // dynamically adjusts capacity as needed.
- public void enqueue(Object obj) throws QueueOverflowException{
- Node n=new Node(obj,null);
- if(f==null){
- f=n;
- r=n;
- }
- else{
- r.next=n;
- r=n;
- }
- size++;
- }
- // Removes the item in the front of the queue, throwing the
- // QueueUnderflowException if the queue is empty.
- public Object dequeue() throws QueueUnderflowException{
- Node rn=null;
- Object val=null;
- if(size==0)
- throw new QueueUnderflowException();
- else if(r==f){
- val=f.element;
- rn=f;
- r=null;
- f=null;
- }
- else{
- val=f.element;
- rn=f;
- f=f.next;
- }
- rn.element=null;
- rn.next=null;
- rn=null;
- size--;
- return val;
- }
- // Peeks at the item in the front of the queue, throwing
- // QueueUnderflowException if the queue is empty.
- public Object peek() throws QueueUnderflowException{
- if(size==0)
- throw new QueueUnderflowException();
- return f.element;
- }
- // Returns a textual representation of items in the queue, in the
- // format "[ x y z ]", where x and z are items in the front and
- // back of the queue respectively.
- public String toString(){
- String str="";
- for(Node n=f;n!=null;n=n.next){
- str+=n.element+" ";
- }
- return "[ "+str+" ]";
- }
- // Returns an array with items in the queue, with the item in the
- // front of the queue in the first slot, and back in the last slot.
- public Object[] toArray(){
- Object[]temp=new Object[size()];
- int i=0;
- for(Node n=f;n!=null;n=n.next){
- temp[i]=n.element;
- i++;
- }
- return temp;
- }
- // Searches for the given item in the queue, returning the
- // offset from the front of the queue if item is found, or -1
- // otherwise.
- public int search(Object obj){
- int count=0;
- for(Node n=f;n!=null;n=n.next){
- if(obj.equals(n.element)){
- return count;
- }
- count++;
- }
- return -1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement