数据结构-线性结构-队列

>数组队列

public class ArrayQueueDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ArrayQueue arr = new ArrayQueue(3);
		arr.add(2);
		arr.add(4);
		
		System.out.println(arr.isFull());
		System.out.println(arr.headQueue());
		arr.showQueue();
		System.out.println(arr.getQueue());

	}
	

}

class ArrayQueue{
	private int maxSize; //表示数组的最大容量
	private int front;//队列头
	private int rear;//队列尾
	private int[] arr;//该数据用于存放数据,模拟队列
	
	public ArrayQueue(int arrMaxSize){
		maxSize = arrMaxSize;
		arr = new int[maxSize];
		front = -1; //指向队列头部,分析出front是指向队列头的前一个位置
		rear = -1; //指向队列尾部,指向队列尾的数据(即队列的最后一个数据)
	}
	
	//判断队列是否已满
	public boolean isFull(){
		return maxSize-1 == rear ;
	}
	
	//判断队列是否为空
	public boolean isEmpty(){
		return front == rear;
	}
	
	//添加数据队列
	public void add(int n){
		if(isFull()){
			System.out.println("队列已满");
			return;
		}
		
		rear++;
		arr[rear] = n;
	
	}
	
	//获取队列数据
	public int getQueue(){
		if(isEmpty()){
			throw new RuntimeException("队列为空,不能取数据");
		}
		
		front++;
		return arr[front];
	}
	//显示队列所有数据
	public void showQueue(){
		//遍历
		if(isEmpty()){
			System.out.println("队列为空");
			return;
		}
		
		for(int i=0;i<arr.length;i++){
			System.out.printf("arr[%d]=%d\n", i,arr[i]);
		}
	}
	
	//显示队列的头数据
	public int headQueue(){
		if(isEmpty()){
			throw new RuntimeException("头数据为空");
		}
		return arr[front+1];
	}
	
}

但是会导致队列前的空间发生浪费,数组使用一次就不能复用,因此需要环形队列。

class CircleArray{
	private int maxSize; //表示数组的最大容量
	private int front;//队列头
	private int rear;//队列尾
	private int[] arr;//该数据用于存放数据,模拟队列
	
	public CircleArray(int arrMaxSize){
		maxSize = arrMaxSize;
		arr = new int[maxSize];
		front = 0; //front指的是队列的第一个元素,也就是arr[fornt]
		rear = 0; //指向队列最后一个元素的后一个位置
	}
	
	//判断队列是否已满
	public boolean isFull(){
		return (rear+1) % maxSize == front ;
	}
	
	//判断队列是否为空
	public boolean isEmpty(){
		return front == rear;
	}
	
	//添加数据队列
	public void add(int n){
		if(isFull()){
			System.out.println("队列已满");
			return;
		}
		
		arr[rear] = n;
		rear = (rear+1) % maxSize;
	
	}
	
	//获取队列数据
	public int getQueue(){
		if(isEmpty()){
			throw new RuntimeException("队列为空,不能取数据");
		}
		

		int value = arr[front];
		front = (front+1) % maxSize;
		return value;
	}
	
	//求出队列当前有效数据个数
	public int size(){
		return (rear-front+maxSize) % maxSize;
	}
	//显示队列所有数据
	public void showQueue(){
		//遍历
		if(isEmpty()){
			System.out.println("队列为空");
			return;
		}
		
		for(int i=front;i<size();i++){
			System.out.printf("arr[%d]=%d\n", i % maxSize,arr[i % maxSize]);
		}
	}
	
	//显示队列的头数据
	public int headQueue(){
		if(isEmpty()){
			throw new RuntimeException("头数据为空");
		}
		return arr[front];
	}
	
}
发布了27 篇原创文章 · 获赞 1 · 访问量 2021

猜你喜欢

转载自blog.csdn.net/yangyiyun199863/article/details/104821456