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 ArrayQueue {
- // The number of items in the queue
- int f;
- int r;
- int size;
- Object [] cir;
- public ArrayQueue(){
- f=-1;
- r=-1;
- size=0;
- cir=new Object [10];
- }
- public int size(){
- return size;
- }
- // Returns true if the queue is empty
- public boolean isEmpty(){
- if(size==0 || f==-1)
- 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{
- if(size==cir.length)
- throw new QueueOverflowException();
- else if(size==0){
- f=0;
- r=0;
- cir[r]=obj;
- }
- else{
- r=(r+1)%cir.length;
- cir[r]=obj;
- }
- size++;
- }
- // Removes the item in the front of the queue, throwing the
- // QueueUnderflowException if the queue is empty.
- public Object dequeue() throws QueueUnderflowException{
- Object val=null;
- if(size==0)
- throw new QueueUnderflowException();
- else if(f==r){
- val=cir[f];
- cir[f]=null;
- f=0;
- r=0;
- }
- else{
- val=cir[f];
- cir[f]=null;
- f=(f+1)%cir.length;
- }
- 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 cir[f];
- }
- // 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="";
- int k=f;
- for(int i=0;i<size();i++){
- str+=cir[k]+" ";
- k=(k+1)%cir.length;
- }
- 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 k=f;
- for(int i=0;i<size();i++){
- temp[i]=cir[k];
- k=(k+1)%cir.length;
- }
- 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 k=f;
- for(int i=0;i<size();i++){
- if(obj.equals(cir[k])){
- return i;
- }
- k=(k+1)%cir.length;
- }
- return -1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement