zoukankan      html  css  js  c++  java
  • 基本数据结构——队列

      队列实现的是一种先进先出(first-in, first-out, FIFIO)的策略,队列中的插入的操作称为入队(enqueue),队列的删除操作称为出队(dequeue)。

    使用一个数组S[n]来实现容量为n-1的队列,定义属性head和tail分别指向对列的第一个元素和下一个新元素要插入的位置。代码实现如下:

    //定义一个数组来实现队列
    public class Queue {
        private Object[] objs;
        private int head = 0;    //指向第一个元素
        private int tail = 0;    //指向新元素将要插入的位置
        
        public Queue() {
        }
        
        public Queue(int n) {
            objs = new Object[n];    //初始化数组大小
        }
        
        public boolean isEmpty() {  
            if(tail == head) {
                return true;
            }
            else{
                return false;
            }
        }
        
        public boolean isFull() {
            if(head == 0 && tail == objs.length-1){
                return true;
            }
            if(head == tail+1){
                return true;
            }else{
                return false;
            }
        }
        
        public boolean enqueue(Object obj) {
            if(!isFull()) {
                objs[tail] = obj;
                if(tail == objs.length-1) {
                    tail = 0;
                }else{
                    tail += 1;                
                }
                return true;
            }else{
                return false;
            }
        }
        
        public Object dequeue() {
            if(isEmpty()) {
                return null;
            }else{
                Object o = objs[head];
                if(head == objs.length-1) {
                    head = 0;
                }else{
                    head = head+1;                
                }
                return o;
            }
        }
        
        public static void main(String[] args) {
            Queue q = new Queue(10);
            
            for(int i=0;i<11;i++) {
                if(q.enqueue(i)) {
                    System.out.println(i);
                }
            }        
            System.out.println();
            for(int i=0;i<11;i++) {
                System.out.println(q.dequeue());
            }
        }
        
    }

    运行结果:

    0
    1
    2
    3
    4
    5
    6
    7
    8

    0
    1
    2
    3
    4
    5
    6
    7
    8
    null
    null

  • 相关阅读:
    react
    问题总结21-07-12至21-08-15
    排序
    问题总结21-06-28至21-07-11
    问题总结21-06-14至21-06-27
    问题总结21-05-29至21-06-13
    问题总结21-04-19至21-05-28
    问题总结21-03-29至21-04-18
    问题总结21-03-08至21-03-28
    问题总结21-03-01至21-03-07
  • 原文地址:https://www.cnblogs.com/ming-zi/p/6373978.html
Copyright © 2011-2022 走看看