Java实现队列

class Element{
    int id;
    String name;
    Element(int a,String n){
        id=a;name=n;
    }
}

class SeqQueue{
    int first,last,maxsize;
    Element queue[];
    SeqQueue(int i){
        maxsize=i;
        first=last=-1;
        queue=new Element[i];
    }
   
    public void clear(){//置空
        first=last=-1;
    }
   
    public boolean isEmpty(){//判空
        if(first==-1)return true;
        else return false;
    }
   
    public Element getFirst(){//取队列头元素
        if(first==-1)return null;
        else return queue[first+1];
    }
   
    public boolean isFull(){//判满
        if((last+1)%maxsize==first)return true;
        else return false;
    }
   
    public boolean enQueue(Element e){//入队
        if(this.isFull())return false;
        if(this.isEmpty())
            first=last=0;
        else
            last=(last+1)%maxsize;
        queue[last]=e;
        return true;
    }
   
    public Element deQueue(){//出队
        Element t=queue[first];
        if(this.isEmpty())return null;
        if(first==last){
            queue[first]=null;
            this.clear();
            return t;
        }
        queue[first]=null;
        first=(first+1)%maxsize;
        return t;
    }
   
    public int getLength(){//队列长度
        if(last>=first)return last-first+1;
        else return maxsize-(first-last)+1;
    }
   
    public void display(){//打印所有元素
        int i,j;
        for (i=first,j=0;j<this.getLength();i=(i+1)%maxsize,j++)
            System.out.println(queue[i].id);
    }
} 

 

posted @ 2014-09-03 10:01  GisClub  阅读(565)  评论(0编辑  收藏  举报