模拟一个队列(java)

[size=medium]简介[/size]
队列是一种特殊的线性表,它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作。进行插入操作的端称为队尾,进行删除操作的端称为队头。队列中没有元素时,称为空队列。
在队列这种数据结构中,最先插入的元素将是最先被删除的元素;反之最后插入的元素将最后被删除的元素,因此队列又称为“先进先出”(FIFO—first in first out)的线性表。   
队列空的条件: front=rear   
队列满的条件: rear = MAXSIZE


/**
* simulate queue struct by java
*
* @author Bruce
* @date Sep 8, 2011
* @version 1.0
*/

public class Queue {
private int maxSize;
private long[] queueArray;
private int front;// the head of queue
private int rear;// the end of queue
private int nItems;

/**
* Constructor a queue,the size is s;now the queue is null, and the front is
* zero and the rear is negative one
*
* @param s
*/
public Queue(int s) {
maxSize = s;
queueArray = new long[maxSize];
front = 0;
rear = 0;
nItems = 0;
}

public void insert(long j) {
// if the the inserted items great the size of queue,
// the rear return the initial value and the next item will
// override the corresponding value
if (rear == maxSize)
rear = 0;
queueArray[rear++] = j;
nItems++;// the count of the items
}

/**
* remove the item from the 'front' position,every time the front will be
* added one
*/
public long remove() {
long temp = queueArray[front++];
// if the front equals the size of queue,the front will return the
// initial value
if (front == maxSize)
front = 0;
nItems--;
if (nItems < 0)
nItems = 0;
return temp;
}

public long peekFront() {
return queueArray[front];
}

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

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

public int size() {
return nItems;
}

public static void main(String[] args) {
Queue queue = new Queue(3);
queue.insert(3);
queue.insert(6);
queue.insert(8);
// queue.insert(4);

System.out.println("size:" + queue.size());

System.out.println(queue.peekFront());
queue.remove();
System.out.println(queue.peekFront());
queue.remove();
System.out.println(queue.peekFront());
queue.remove();
// System.out.println(queue.peekFront());
// queue.remove();

System.out.println("size:" + queue.size());

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值