JAVA数据结构之顺序队列的实现

1、顺序队列的实现代码如下所示:

public class SeqQueue {
	private Object array[];
	private int capacity;//队列的最大容量
	private int count;//队列中元素的个数
	private int front;
	private int tail;
	
	public SeqQueue(int capacity){
		array = new Object[capacity];
		this.capacity = capacity;
		count = 0;
		front = 0;
		tail = 0;
	}
	
	//入队
	public boolean insert(Object data){
		boolean ret = (array != null) && (data != null) && (count < capacity);
		
		if(ret){
			array[tail] = data;
			tail = (tail + 1) % capacity;
			count++;
		}
		
		return ret;
	}
	
	//出队
	public Object remove(){
		Object ret = null;
		
		if((array != null) && (count > 0)){
			ret = array[front];
			array[front] = null;
			
			front = (front + 1) % capacity;
			count--;
		}
		
		return ret;
	}
	
	//显示队头元素,不删除。
	public Object getHead(){
		return array[front];
	}
	
	//清空队列
	public void clear(){
		array = null;
		array = new Object[capacity];
		count = 0;
		front = 0;
		tail = 0;
	}
	
	//销毁队列
	public void destroy(){
		array = null;
		count = 0;
		front = 0;
		tail = 0;
	}
	
	//判断队列是否为空
	public boolean isEmpty(){
		return count == 0;
	}
	
	//判断队列是否已满
	public boolean isFull(){
		return count == capacity;
	}
	
	//获取队列中元素的个数
	public int getCount(){
		return count;
	}
	
	//获取队列的容量
	public int getCapacity(){
		return capacity;
	}
}
2、测试代码如下所示:

public class Test {

	public static void main(String[] args) {
		SeqQueue seqQueue = new SeqQueue(5);
		seqQueue.insert("Android");
		seqQueue.insert("IOS");
		seqQueue.insert("Java");
		seqQueue.insert("C++");
		seqQueue.insert("C");
		seqQueue.insert("C#");
		seqQueue.insert("python");
		
		System.out.println("队列的容量:"+seqQueue.getCapacity());
		System.out.println("队列中元素的个数:"+seqQueue.getCount());
		System.out.println("队头元素:"+seqQueue.getHead());
		System.out.println("队列是否为空?"+seqQueue.isEmpty());
		System.out.println("出队:");
		
		while(!seqQueue.isEmpty()){
			System.out.print(seqQueue.remove()+"  ");
		}
		
		seqQueue.clear();
		System.out.println("\n队列中元素的个数:"+seqQueue.getCount());
		seqQueue.destroy();
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值