1. 程式人生 > >C++ 環形佇列 入隊 出隊 遍歷

C++ 環形佇列 入隊 出隊 遍歷

#include "stdafx.h"
#include <iostream>

using namespace std;

/*struct Node
{
int elem;
Node *link;
};*/

class STACK
{
public:
    STACK(int size);    //棧初始空間,容量,棧頂
    ~STACK();     //回收記憶體
    bool enqueue(int obj);   //判滿
    bool outqueue(int &elem);   //判空,出棧
    void clear();
    bool empty();
    bool full();
    int length();
    void traverse();
private:
    int *top; //棧頂指標
    int m_size;
    int m_length;
    int ihead;
    int itial;
};
STACK::STACK(int size)
{
    m_size = size;
    top = new int(m_size);
    m_length = 0;
    ihead = 0;
    itial = 0;
}
STACK ::~STACK()
{
    delete []top;
}

void STACK::clear()
{
    m_length = 0;
    ihead = 0;
    itial = 0;
}
int STACK::length() {

    return m_length;
}
bool STACK::empty()
{
    if (m_length == 0)
    {
        return true;
    }
    else
        return false;
}
bool STACK::full()
{
    if (m_length == m_size)
    {
        return true;
    }
    return false;
}
bool STACK::enqueue(int obj) {
    if (m_length == m_size)
    {
        cout << "full" << endl;
        return false;
    }
    top[itial] = obj;
    itial++;
    itial = itial%m_size;
    m_length++;
    return true;
}
bool STACK::outqueue(int &elem) {
    if (m_length == 0)
    {
        cout << "empty" << endl;
        return false;
    }
    elem = top[ihead];
    ihead++;
    ihead = ihead%m_size;  //z環形
    m_length--;
    return true;
}

void STACK::traverse() {

    //for (int i = 0; i < m_length; i++)
    for (int i = ihead; i < m_length + ihead; i++)
        cout << top[i%m_size] << " ";
}
int main() {
    STACK *st=new STACK(5);
    //STACK st(5);
    st->enqueue(10);
    st->enqueue(11);
    st->enqueue(12);
    st->enqueue(13);
    st->enqueue(14);
    int e = 0;
    st->outqueue(e);
    cout << e << endl;
    st->outqueue(e);
    cout << e << endl;
//    cout << st->length() << endl;
    st->traverse();
    delete st;
    //st.~STACK();
    //st = NULL;
    system("pause");
    return 0;
}