循环队列java

来源:互联网 发布:python 2.7 降级2.6 编辑:程序博客网 时间:2024/06/06 15:46
import java.lang.*;


public class queue{
public static void main(String args[]){
sq_queue sq = new sq_queue(10);//实例化循环队列
for(int i = 1; i < 10; i++){//入队一些数据
sq.ins_queue(i);
}
sq.print_queue();
sq.del_queue();
sq.del_queue();
sq.del_queue();
sq.print_queue();
sq.ins_queue(10);
sq.ins_queue(20);
sq.ins_queue(30);
sq.ins_queue(40);
sq.print_queue();
sq.del_queue();
sq.del_queue();
sq.del_queue();
sq.del_queue();
sq.del_queue();
sq.del_queue();
sq.del_queue();
sq.del_queue();
sq.del_queue();
sq.del_queue();
sq.print_queue();
}
}
//循环队列类
class sq_queue{
private int front;//头指针
private int rear;//尾指针
private boolean flag;//头指针=尾指针不一定说明队列满,还可能是空
private int queue[];//头指针
private int m;//头指针
//构造函数,初始化队列
public sq_queue(int m){
this.m = m;
front = 0;
rear = 0;
queue = new int[m];
flag = false;
}
//入队
public void ins_queue(int num){
if(flag && front == rear){//判断队列是否为满
System.out.println("队列已满。。。");
return;
}
rear++; //尾指针加一
queue[rear - 1] = num;//在尾指针前面插入入队数
System.out.println("front="+front+",rear="+rear + ",入队元素为:" + num);
if(rear == m){//判断是否达到数组的最后,是的话,尾指针连接到首位
rear = 0;
}
flag = true; //队列非空
}
//出队
public void del_queue(){
if(!flag && front == rear){//判断队列是否为空
System.out.println("队列为空。。。");
return;
}
front++; //头指针加一,指向新的头元素
System.out.println("front="+front+",rear="+rear + ",出队元素为:" + queue[front - 1]);
if(front == m){//判断是否达到数组的最后,是的话,头指针连接到首位
front = 0;
}
if(front == rear){//头指针追上尾指针的时候说明数组为空了
flag = false;
}
}
//打印队列
public void print_queue(){
if(!flag && front == rear){//判断队列是否为空,因为本例子没有删除队列中的元素,只是靠头尾指针操作,所以要判断
System.out.println("队列为空。。。");
return;
}
int i = front;
do{ //当队列为满的时候,front = rear,所以要先打印一个,否则无法输出,不能使用while循环
System.out.println("front:" + front + ",rear:" + rear + ",elemrnt=" +queue[i] + " ");
i++;
if(i == m){
i = 0;
}
}while(i != rear);
System.out.println();
}
}
0 0
原创粉丝点击