zoukankan      html  css  js  c++  java
  • 【数据结构基础】——队列、栈

    1、先入先出的数据结构 —— 栈

      1.1、定义及基本操作

                               

        在FIFO数据结构中,将首先处理添加到队列中的第一个元素。如上图所示,队列是典型的FIFO数据结构。插入(insert)操作也成为入队(enqueue),新元素始终被添加在队列的末尾。删除(delete)也被称为出队(dequeue),你只能移除第一个元素

            新元素6的入队操作如下:

              

              第一个元素元素5出队操作如下:

                       

      1.2、实现

        为了实现队列,我们可以使用动态数组和指向队列头部的索引。

        如上所述,队列应支持两种操作:入队和出队。入队会向队列追加一个新元素,而出队会删除第一个元素。 所以我们需要一个索引来指出起点。

        这是一个供你参考的实现:

     1 // "static void main" must be defined in a public class.
     2 
     3 class MyQueue {
     4     // store elements
     5     private List<Integer> data;         
     6     // a pointer to indicate the start position
     7     private int p_start;            
     8     public MyQueue() {
     9         data = new ArrayList<Integer>();
    10         p_start = 0;
    11     }
    12     /** Insert an element into the queue. Return true if the operation is successful. */
    13     public boolean enQueue(int x) {
    14         data.add(x);
    15         return true;
    16     };    
    17     /** Delete an element from the queue. Return true if the operation is successful. */
    18     public boolean deQueue() {
    19         if (isEmpty() == true) {
    20             return false;
    21         }
    22         p_start++;
    23         return true;
    24     }
    25     /** Get the front item from the queue. */
    26     public int Front() {
    27         return data.get(p_start);
    28     }
    29     /** Checks whether the queue is empty or not. */
    30     public boolean isEmpty() {
    31         return p_start >= data.size();
    32     }     
    33 };
    34 
    35 public class Main {
    36     public static void main(String[] args) {
    37         MyQueue q = new MyQueue();
    38         q.enQueue(5);
    39         q.enQueue(3);
    40         if (q.isEmpty() == false) {
    41             System.out.println(q.Front());
    42         }
    43         q.deQueue();
    44         if (q.isEmpty() == false) {
    45             System.out.println(q.Front());
    46         }
    47         q.deQueue();
    48         if (q.isEmpty() == false) {
    49             System.out.println(q.Front());
    50         }
    51     }
    52 }
  • 相关阅读:
    音频、视频等文件格式(.ts、.meta)及其认识
    元素之和最接近 0 的区间(部分和)
    元素之和最接近 0 的区间(部分和)
    说话的智慧
    说话的智慧
    工业相机基本参数以及选型参考(二)
    常用编程软件站点、镜像站、科技类 PDF
    常用编程软件站点、镜像站、科技类 PDF
    经典书单 —— 语言/算法/机器学习/深度学习/AI/CV/PGM
    hdu1024 Max Sum Plus Plus
  • 原文地址:https://www.cnblogs.com/ouhouki/p/10830472.html
Copyright © 2011-2022 走看看