顺序队列——用数组实现

本文介绍了如何使用数组在Java中实现顺序队列,探讨了在入队操作时的数据搬移策略。

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

队列笔记1——用数组实现队列

package queue;
/*
 * 用数组实现的队列
 */
public class queue {
		
		private String[] items;
		private int n=0;
		//head表示队头下标,tail表示队尾下标
		private int head=0;
		private int tail=0;
		//申请一个大小为capacity的数组
		public queue(int capacity)
		{
			items=new String[capacity];
			n=capacity;
		}
		//入队
		public boolean enqueue(String item)
		{
			if(tail==n)return false;//如果tail == n 表示队列已经满了
			items[tail]=item;
			++tail;
			return true;
		}
		//出队
		public String dequeue()
		{
			if(head==tail) return null;//如果head == tail 表示队列为空
			String ret=items[head];
			++head;
			return ret;
		}
		public void printAll()
		{
			for(int i=head;i<tail;i++)
			{
				System.out.print(items[i]+" ");
			}
			System.out.println();
		}
		
}

如果没有空闲时间了,只需在入队时再集中触发一次数据的搬移,代码更新为:

package queue;
/*
 * 用数组实现的队列
 */
public class queue {
		
		private String[] items;
		private int n=0;
		//head表示队头下标,tail表示队尾下标
		private int head=0;
		private int tail=0;
		//申请一个大小为capacity的数组
		public queue(int capacity)
		{
			items=new String[capacity];
			n=capacity;
		}
		//入队
//		public boolean enqueue(String item)
//		{
//			if(tail==n)return false;//如果tail == n 表示队列已经满了
//			items[tail]=item;
//			++tail;
//			return true;
//		}
		//如果没有空闲时间了,只需在入队时再集中触发一次数据的搬移
		public boolean enqueue(String item)
		{
			if(tail==n)//表示队列末尾没有空间了
			{
				if(head==0) return false;//表示整个队列都占满了
				for(int i=head;i<tail;i++)//数据的搬移
				{
					items[i-head]=items[i];
				}
				tail=tail-head;//搬移完之后再重新更新head和tail
				head=0;
			}
			items[tail]=item;
			++tail;
			return true;
		}
		//出队
		public String dequeue()
		{
			if(head==tail) return null;//如果head == tail 表示队列为空
			String ret=items[head];
			++head;
			return ret;
		}
		public void printAll()
		{
			for(int i=head;i<tail;i++)
			{
				System.out.print(items[i]+" ");
			}
			System.out.println();
		}
		
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值