美文网首页
数据结构 第2讲 队列

数据结构 第2讲 队列

作者: 逸軒 | 来源:发表于2019-03-13 21:14 被阅读0次

    一、概述
    队列:一种只允许在一端进行插入,在另一端进行删除的线性表结构。运行插入的一端叫队尾,允许删除的一端叫队头。
    二、顺序存储结构的队列基本操作以及算法实现
    基本操作:入队、出对、队列里的元素数量、置空队列、判断是否为空、读取队列头部首元素等。


    image.png
    //数组实现"队列",只能存储int数据
    public class Array {
      private int[] array;
      private int count;
      
      private Array(int size){
        array = new int[size];
        count = 0;
      }
      // 将t添加到队列的末尾
      public void add(int t){
          array[count++] = t;
      }
      // 返回"队列开头元素"
      public int front(){
          return array[0];
      }
      // 返回"栈顶元素值",并删除"栈顶元素"
      public int pop(){
          int ret = array[0];
          count--;
          for (int i =1; i <=count; i++) {
            array[i-1] = array[i];
        }
          return ret;
      }
      // 返回"栈"的大小
      public int size() {
          return count;
      }
    
      // 返回"栈"是否为空
      public boolean isEmpty() {
          return size()==0;
      }
    
      public static void main(String[] args) {
          int string= 30;
          Array stack = new Array(12);
    
          // 将10, 20, 30 依次推入栈中
          stack.add(10);
          stack.add(20);
          stack.add(30);
    
          // 将"栈顶元素"赋值给string,并删除"栈顶元素"
          string = stack.pop();
          System.out.printf("string=%d\n",string);
    
          // 只将"栈顶"赋值给string,不删除该元素.
          string = stack.front();
          System.out.printf("string=%d\n",string);
    
          stack.add(10);
    
          System.out.printf("isEmpty()=%b\n", stack.isEmpty());
          System.out.printf("size()=%d\n", stack.size());
          while (!stack.isEmpty()) {
              System.out.printf("size()=%d\n", stack.pop());
          }
      }
    }
    
    image.png image.png

    相关文章

      网友评论

          本文标题:数据结构 第2讲 队列

          本文链接:https://www.haomeiwen.com/subject/dfpapqtx.html