1. 程式人生 > >C++之棧的實現

C++之棧的實現

MyStack.h

class MyStack
{
public:
    MyStack(int Size);//分配記憶體初始化棧空間,設定棧容量,棧頂
    ~MyStack();//回收棧空間記憶體
    bool stackEmpty();//判定棧是否為空
    bool stackFull();//判定棧是否滿
    void clearStack();//清空棧
    int stackLength();//已有元素的個數
    bool push(char elem);//元素入棧
    bool pop(char &elem);//元素初棧
    void stackTraverse();//遍歷棧中所有元素
private: char *m_pBuffer;//棧空間指標 int m_iSize;//棧容量 int m_iTop;//棧頂,棧中元素個數 };

MyStack.cpp

#include "MyStack.h"
#include <iostream>
using namespace std;

MyStack::MyStack(int Size)
{
    m_iSize = Size;
    m_pBuffer = new char[Size];
    m_iTop = 0;
}

MyStack::~MyStack()
{
    delete []m_pBuffer;
    m_pBuffer = NULL;
}

bool
MyStack::stackEmpty() { if(0 == m_iTop){ return true; } return false; } bool MyStack::stackFull() { if(m_iTop == m_iSize){ return true; } return false; } void MyStack::clearStack() { m_iTop = 0; } int MyStack::stackLength() { return m_iTop; } bool MyStack::push(char
elem) { if(stackFull()){ return false; } m_pBuffer[m_iTop] = elem; m_iTop ++; return true; } bool MyStack::pop(char &elem) { if(stackEmpty()){ return false; } m_iTop --; elem = m_pBuffer[m_iTop]; return true; } void MyStack::stackTraverse() { for(int i=0;i<m_iTop;i++){ cout<<m_pBuffer[i]<<","; } }

main.cpp(隨手測試)

#include <iostream>
#include <stdlib.h>
#include "MyStack.h"
using namespace std;
int main()
{
    MyStack *pStack = new MyStack(5);

    pStack->push('h');//底
    pStack->push('e');
    pStack->push('l');
    pStack->push('l');
    pStack->push('o');//頂

    pStack->stackTraverse();

    char elem = 0;
    pStack->pop(elem);
    cout<<endl;
    cout<<elem<<endl;

    pStack->stackTraverse();

    //pStack->clearStack();

    cout<<pStack->stackLength()<<endl;

    if(pStack->stackEmpty()){
        cout<<"棧為空"<<endl;
    }

    if(pStack->stackFull()){
        cout<<"棧為滿"<<endl;
    }


    delete pStack;
    pStack = NULL;
    system("pause");
    return 0;
}