队列

    xiaoxiao2021-04-15  24

      队列就是一个队伍,由一段连续的存储空间组成,是满足先进先出的数据结构。

          队列是一种受限的数据结构,插入操作只能从一端操作,这一端叫做对尾;而移除操作也只能从另一端操作,这一端叫做队头。

          队列的实现方式:

              (1)数组: 顺序队列、循环队列

              (2)链表 

          队列的适用场景: 缓冲器、解耦

            队列和栈的互相转换: 两个栈实现一个队列和两个队列实现一个栈

       

          顺序队列的代码实现:

    package com.threeTop.www; /*** * 顺序队列的实现 * @author wjgs * */ public class ArrayQueue { private final Object[]items; private int head=0; private int tail=0; /*** * 初始化队列 * @param args */ public ArrayQueue(int capacity) { this.items=new Object[capacity]; } /*** * 入队 * @param item */ public boolean put(Object item) { if(head==(tail+1)%items.length) { //说明队列已经满了 return false; } items[tail]=item; tail=(tail+1)%items.length; //tail 标记向后移动一位 return true; } /*** * 获取队列头的元素,不出队 * @param args */ public Object peek() { if(head==tail) { //队列为空 return null; } return items[head]; } /*** * 出队 * @param args */ public Object poll() { if(head==tail) { //说明队列为空 return null; } Object item=items[head]; items[head]=null; //删除元素的值 head=(head+1)%items.length; //head标记向后移动一位 return item; } /*** * 判断队列是否为满 * @param args */ public boolean isFull() { return head==(tail+1)%items.length; } /** * 判断队列是否为空 * @param args */ public boolean isEmpty() { return head==tail; } /*** * 获得队列的大小 * @param args */ public int size() { if(tail>head) { return tail-head; } else { return tail+items.length-head; } } public static void main(String[] args) { // TODO Auto-generated method stub ArrayQueue queue=new ArrayQueue(4); System.out.println(queue.put("A")); System.out.println(queue.put("B")); System.out.println(queue.put("C")); System.out.println(queue.put("D")); System.out.println(queue.isFull()); System.out.println(queue.size()); System.out.println(queue.peek()); System.out.println(queue.poll()); System.out.println(queue.poll()); System.out.println(queue.poll()); System.out.println(queue.isEmpty()); /**多设置了一个位置来解决问题,声明的长度是4,但是只能存放3个元素 * 输出结果 * true         true          true         false         true         3         A         A         B         C         true */ } }

         

    转载请注明原文地址: https://ju.6miu.com/read-671667.html

    最新回复(0)