首页 > 其他 > 详细

队列&栈

时间:2021-08-17 20:35:57      阅读:11      评论:0      收藏:0      [点我收藏+]
  1. 先入先出(FIFO)的数据结构
    入队(enqueue)和出队(dequeue)
    队列是典型的FIFO数据结构

  2. 实现队列
    为了实现队列,可以使用动态数组和指向数组头部的索引;一个队列最主要的操作为入队和出队,可以将它们设置为返回值为布尔值的函数,操作成功返回true,操作失败返回false。还需要一个显示队列头元素的函数和一个判断队列是否为空的函数

#include <iostream>

class MyQueue {
   private:
       // store elements
       vector<int> data;       
       // a pointer to indicate the start position
       int p_start;            
   public:
       MyQueue() {p_start = 0;}
       /** Insert an element into the queue. Return true if the operation is successful. */
       bool enQueue(int x) {
           data.push_back(x);
           return true;
       }
       /** Delete an element from the queue. Return true if the operation is successful. */
       bool deQueue() {
           if (isEmpty()) {
               return false;
           }
           p_start++;
           return true;
       };
       /** Get the front item from the queue. */
       int Front() {
           return data[p_start];
       };
       /** Checks whether the queue is empty or not. */
       bool isEmpty()  {
           return p_start >= data.size();
       }
};

int main() {
   MyQueue q;
   q.enQueue(5);
   q.enQueue(3);
   if (!q.isEmpty()) {
       cout << q.Front() << endl;
   }
   q.deQueue();
   if (!q.isEmpty()) {
       cout << q.Front() << endl;
   }
   q.deQueue();
   if (!q.isEmpty()) {
       cout << q.Front() << endl;
   }
}

队列&栈

原文:https://www.cnblogs.com/starkly/p/15153269.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!