循環隊列的面向對象實現(C++)

</pre><pre name="code" class="cpp">/*************************************************************************
	> File Name: CycleQueue.cpp
	> Author: Shaojie Kang
	> Mail: [email protected] 
	> Created Time: 2015年09月16日 星期三 10時14分01秒 
    > Problem:
        循環隊列
 ************************************************************************/

#include<iostream>
using namespace std;
const int capacity = 20;

template <class T>
class Queue 
{
private:
    int head;
    int tail;
    int qsize;
    int *base;
public:
    Queue(): head(0), tail(0), qsize(0)
    {
        base = new T[capacity];
    }

    ~Queue()
    {
        delete []base;
    }

    int size()
    {
        return qsize;
    }

    bool empty()
    {
        return (head == tail); 
    }

    bool full()
    {
        return head == (tail + 1)%capacity;
    }

    void push(T x)
    {
        if(full()) return;
        *(base + tail) = x;
        tail = (tail + 1) % capacity;
        qsize++;
    }

    void pop()
    {
        if(empty()) return;
        head = (head + 1) % capacity;
        qsize--;
    }

    T front()
    {
        if(empty()) return -1;
        return *(base + head);
    }
};

int main()
{
    Queue<int> q;
    int arr[] = {
        3,1, 2, 9, 4, 3
    };
    cout<<q.size()<<endl;
    for(int i = 0; i < 3; ++i)
    {
        q.push(arr[i]);
    }
    cout<<q.size()<<endl;
    cout<<q.front()<<endl;
    q.pop();
    cout<<q.size()<<endl;
    cout<<q.front()<<endl;
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章