线性表之队列的实现

/**  
* Queue.java
* 线性表之队列
* 队列有如下特点:
* 先进先出
* 即,从尾部添加(push)新数据
* 从头部取出(pop)数据
*/


/**
* 队列(Queue)也是一种运算受限的线性表。
* 它只允许在表的一端进行插入,而在另一端进行删除。
* 允许删除的一端称为队头(front),允许插入的一端称为队尾(rear)。
*/
package line;


/**
* @author sunxboy
* 9:59:59 AM May 22, 2007
*/
public class Queue {

int data[];
int maxSize;
int size;
int front; //允许删除的一端
int rear; //允许插入的一端
public Queue(int maxSize) {
this.maxSize = maxSize;
this.data = new int[maxSize];
size= 0;
rear = 0;
front =0;
}

public boolean isEmpty() {
return size==0;
}

public boolean isFull() {
return size==maxSize;
}

/**
* 循环队列
* @param data
* @return
*/
public boolean push(int data)throws Exception {

if(isFull())
throw new Exception("队列已满!");
size++;
this.data[rear]= data;

// if(rear+1==maxSize)
// rear=0;
// else
// rear++;

rear=(rear+1)%maxSize;

return true;

}

public int pop() throws Exception{
int temp;
if(isEmpty())
throw new Exception("队列是空的.");
temp = this.data[this.front];

this.size--;
// if(front+1==maxSize)
// front=0;
// else
// front++;
front=(front+1)%maxSize;
return temp;
}


public static void main(String[] args) throws Exception{
Queue queue=new Queue(10);
queue.push(1);
queue.pop();
// queue.pop();
queue.push(2);
queue.push(3);
queue.push(4);
queue.push(5);
queue.push(6);
queue.push(7);
queue.push(8);
queue.push(9);
queue.push(10);
// queue.push(11);
while(!queue.isEmpty())
{
System.out.println(queue.pop());
}

}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值