队列的基本实现

来源:互联网 发布:金玉满堂 知乎 编辑:程序博客网 时间:2024/05/18 13:46

队列的基本实现

TIP:宏断言assert(<表达式>);
利用宏断言,如果不满足则说明队列空,直接返回;

#include <iostream>#include <cassert>using namespace std;class Queue {private:    int *data;    int head, tail, length;public:    Queue(int length_input) {        data = new int[length_input];        length = length_input;        head = 0;        tail = -1;    }    ~Queue() {        delete[] data;    }    void push(int element) {        if (tail + 1 < length) {            tail++;            data[tail] = element;        }    }    void output() {        for (int i = head; i <= tail; i++) {            cout << data[i] << " ";        }        cout << endl;    }    int front(){        assert(head<=tail);//利用宏断言,如果不满足则说明队列空,直接返回        return data[head];    }    void pop(){        assert(head<=tail);        head++;    }};int main() {    Queue queue(100);    for (int i = 1; i <= 10; i++) {        queue.push(i);    }    queue.output();    cout<<queue.front()<<endl;    queue.pop();    queue.output();    return 0;}
0 0