java 实现数组队列和链表队列

本文介绍了一种使用数组实现固定大小队列的方法,并提供了一个基于链表的队列实现示例。通过这两种方式,可以有效地进行元素的入队和出队操作,同时还支持队列的清空及检查队列是否为空或已满的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package Queue;
//用数组实现自己的队列
public class Queue {
	private static int DEFAULT_SIZE=100;
	private Object[] queue;
	private int front;
	private int tail;
	private int thelength;
	public Queue(){
		thelength=DEFAULT_SIZE;
		init();
	}
	public Queue(int length){
		thelength=length;
		init();
	}
	
	public int size(){
		return (front-tail+queue.length)%queue.length;
	}
	private void init() {
		queue=new Object[thelength+1];
		tail=front=0;
	}
	
	//入队列
	public void put(Object e) throws Exception{
		if(isFull()){
			throw new Exception("队列已经满了,添加失败!");
		}
		queue[front]=e;
		front=(front+1)%queue.length;	
	}
	
	//出队列
	public Object get() throws Exception{
		if(isEmpty()){
			throw new Exception("队列为空,删除失败!");
		}
		Object e=queue[tail];
		queue[tail]=null;
		tail=(tail+1)%queue.length;
		return e;
	}
	
	//清空队列
	public void clear(){
		queue=null;
		queue=new Object[thelength];
	}
	
	public boolean isEmpty() {
		return front==tail;
	}
	//判断队列是否已满
	public boolean isFull() {
		return (front+1)%queue.length==tail;
	}
	
	public static void main(String[] args){
		Queue que=new Queue(4);
		char[] data=new char[]{'沧', '海','一','声'};
		try {
		for(int i=0;i
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值