循环队列

队列:队列是一种先进先出的线性表,它只允许在表的一端进行插入,而另一端进行删除,允许插入的一端叫做队尾,允许删除的一端叫做对头。
循环队列;
循环队列是一种以顺序存储结构表示的队列,为了解决“假溢出”问题而将它设计成头尾相接的循环结构,它的基本操作如下:
    1、初始化循环队列
    2、销毁循环队列
    3、清空循环队列
    4、检测循环队列是否为空
    5、返回循环队列的元素个数
    6、返回循环队列头元素
    7、向队尾插入元素
    8、删除并返回队头元素
    9、遍历循环队列
在循环队列中,除了用一组地址连续的存储单元依次存储从队头到队尾的元素外,还需要附设两个整型变量front和rear分别指示队头和队尾的位置。
 
 1、定义类属性和构造函数
复制代码
 class InitQueue{
     
     private int [] queue = null;
     
     private int front = 0;
     
     private int rear = 0;
     
     private boolean empty = true;      //true表示循环队列为空
     
     public InitQueue(int max) {       //构造指定大小的循环队列
         this.queue = new int[max];
     }
 }
复制代码

 

 
2、清空循环队列
public void clearQueue() {
    this.front = 0;
    this.rear = 0;
    this.empty = true;
}

 

3、检测循环队列是否为空
public boolean queueEmpty() {
    if(this.empty == true) {
        return true;
    }else {
        return false;
    }
}

 

4、返回循环队列的元素个数
public int queueLength() {
    //如果循环队列已满,返回数组长度即元素个数
    if (this.front == this.rear && this.empty == false) {
        return this.queue.length;                              
    }
    //否则,取模运算得到长度
    return (this.rear - this.front + this.queue.length) % this.queue.length;    
}

 

5、返回循环队列头元素
复制代码
 public int [] getHead() {
 
     if (this.empty == true) {
         return null;
     }
 
     int [] i = new int[1];
     i[0] = queue[this.front];
     return i;
 }
复制代码

 

6、向队尾插入元素
复制代码
 public boolean enQueue(int value) {
 
     if (this.empty == false && this.front == this.rear) {
         return false;
     }
 
     this.queue[this.rear] = value;
     this.rear = (this.rear + 1) % this.queue.length;
     this.empty = false;
     return true;
 }
复制代码

 

7、删除并返回队头元素
复制代码
public int [] deQueue() {
    if (this.empty == true) {
        return null;
    }
    int [] i = new int[1];
    //获取队头元素
    i[0] = this.queue[this.front];                
    //删除队头元素(front指针加一)
    this.front = (this.front + 1) % this.queue.length;
    //如果循环队列变空,改变标志位    
    if(this.front == this.rear) {                 
        this.empty = true;
    }
    return i;
}
复制代码

 

8、遍历循环队列
复制代码
public String queueTraverse() {                    
    //此处用输出循环队列表示遍历
    String s = "";
    //i指向第一个元素
    int i = this.front;                         
    //如果循环队列已满,取出第一个元素,i指向下一个元素
    if(this.front == this.rear && this.empty == false) {     
        s += this.queue[i] + "、";
        i = (i + 1) % this.queue.length;
    }
    //如果未到末尾,则循环读取元素
    while (i != this.rear) {                      
        s += this.queue[i] + "、";
        i = (i + 1) % this.queue.length;
    }
    //如果没有读取到元素,直接返回空字符串
    if(s.length() == 0) {                        
        return s;
    }
    //除去最后的顿号返回
    return s.substring(0,s.length() - 1);              
}
复制代码

 

 
 
 
 
 
 
 
posted @   余额一个亿  阅读(296)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
点击右上角即可分享
微信分享提示