zoukankan      html  css  js  c++  java
  • 用数组实现队列(C++)

    代码:

    #include <iostream>
    #include <string.h>
    #define N 3
    typedef struct Queue
    {
      int a[N];
      int head,tail;
    }Queue;
    void show(Queue* p)
    {
      for(int i=0;i<N;i++)
      {
        std::cout << p->a[i] << ' ';
      }
    }
    void init(Queue* p)
    {
      memset(p->a, 0, sizeof(int)*N);
      p->head = 0;
      p->tail = 0;
    }
    void push(Queue* p,int val)
    {
      ++p->tail;
      if(p->tail > N-1)
      {
        std::cout << "队列溢出" << ' ';
      }
      else
      {
        for (int i = p->tail; i >0; i--)
        {
          *(p->a + i) = *(p->a + i - 1);
        }
        /*
        for(int i = p->tail;i > 0;i--)
        {
          p->a[i] = p->a[i-1];
          std::cout << p->a[i] << ' ';
        }
        */
        p->a[0] = val;
      }
    }
    int pop(Queue* p)
    {
      if(p->tail == -1)
      {
        std::cout << "队列为空!!" << ' ';
      }
      else
      {
        int tem = p->a[p->tail];
        --p->tail;
        std::cout << tem << ' ';
        return tem;
      }
      return 1;
    }
    int main()
    {
      Queue q;
      init(&q);
      std::cout << "push操作:" << ' ';
      for(int i=1;i<N;i++)
      {
        push(&q,i);
      }
      show(&q);
      std::cout << ' ';
      std::cout << "pop操作:" <<' ';
      for(int i=0;i<N;i++)
      {
        pop(&q);
      }
      return 0;
    }
     
    测试结果:
     
  • 相关阅读:
    【luogu4719】动态DP模板 [动态DP]
    【2019.9.22】
    [JSOI2010]连通数[tarjan缩点]
    【2019.9.16】Za
    【2019.9.18】Za
    [USACO14OPEN]GPS的决斗Dueling GPS's [最短路]
    【CF891C】Envy [最小生成树]
    【2019.9.17】Za
    【2019.9.17】
    【luogu3403】跳楼机 [同余最短路]
  • 原文地址:https://www.cnblogs.com/shiheyuanfang/p/13582476.html
Copyright © 2011-2022 走看看