quyuq04301991 2015-01-18 04:22 采纳率: 100%
浏览 3127
已采纳

求C++语言用数组实现一个队列的数据结构的完整代码

提示:定义一个数组,用两个指针表示队列的首尾位置,编写两个函数代表出队入队操作。当队列长度超过数组长度时,提示队列超长,当队列空时,提示队列为空。主程序实现对队列的调用,

  • 写回答

2条回答 默认 最新

  • threenewbee 2015-01-18 05:54
    关注
     #include <iostream>
    using namespace std;
    
    #define ARRSIZE 5
    
    class Queue
    {
    private:
        int * arr;
        int * start;
        int * end;
        int length;
    public:
        Queue()
        {
            arr = new int[ARRSIZE];
            start = end = arr;
            length = 0;
        }
        void enqueue(int x)
        {
            if (length == ARRSIZE)
            {
                cout << "full" << endl;
                throw "error";
            }
            else
            {
                *start = x;
                *start--;
                length++;
                if (start < arr) start = &arr[ARRSIZE - 1];
            }
        }
        int dequeue()
        {
            if (!length)
            {
                cout << "empty" << endl;
                throw "error";
            }
            else
            {
                int result = *end;
                *end--;
                length--;
                if (end < arr) end = &arr[ARRSIZE - 1];
                return result;
            }
    
        }
    };
    
    int main(int argc, _TCHAR* argv[])
    {
        Queue q = Queue();
        q.enqueue(1);
        cout << q.dequeue() << endl;
        q.enqueue(2);
        q.enqueue(3);
        cout << q.dequeue() << endl;
        cout << q.dequeue() << endl;
        q.enqueue(4);
        q.enqueue(5);
        q.enqueue(6);
        cout << q.dequeue() << endl;
        cout << q.dequeue() << endl;
        q.enqueue(7);
        cout << q.dequeue() << endl;
        cout << q.dequeue() << endl;
        q.enqueue(8);
        cout << q.dequeue() << endl;
        return 0;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求指导ADS低噪放设计
  • ¥15 CARSIM前车变道设置
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存