首页 > 代码库 > C++__顺序栈(练习)

C++__顺序栈(练习)

顺序栈

 

stack.h

#ifndef STACK_H_
#define STACK_H_

#define STACK_SIZE 5

typedef int data_type;

enum STACK_OP {
    STACK_ERR = -1, STACK_OK, STACK_EMPTY
};

class STACK {
private:
    data_type data[STACK_SIZE];
    int Top;
public:
    STACK();
    ~STACK();

    data_type getData(unsigned int i) const;
    int getTop() const;
    void setData(data_type data, unsigned int i);
    void setTop(int top);

    int Push(STACK *pStack, data_type tData);
    int Pop(STACK *pStack, data_type *pData);
    int IsEmpty(STACK *pStack);
};

#endif /* STACK_H_ */

 

stack.cpp

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

STACK::STACK() {
    // TODO Auto-generated constructor stub
}

STACK::~STACK() {
    // TODO Auto-generated destructor stub
}

data_type STACK::getData(unsigned int i) const {
    return data[i];
}

int STACK::getTop() const {
    return Top;
}

void STACK::setData(data_type data, unsigned int i) {
    this->data[i] = data;
}

void STACK::setTop(int top) {
    this->Top = top;
}

int STACK::Push(STACK *pStack, data_type tData) {
    if (!pStack)
        return STACK_ERR;

    if (pStack->getTop() == STACK_SIZE) {
        cout << "push over" << endl;
        return STACK_ERR;
    }
    pStack->setData(tData, pStack->getTop());
    pStack->setTop(pStack->getTop() + 1);

    return STACK_OK;
}

int STACK::Pop(STACK *pStack, data_type *pData) {
    if ((!pStack) || (!pData))
        return STACK_ERR;

    if (pStack->getTop() == 0) {
        cout << "pop over" << endl;
        return STACK_ERR;
    }
    pStack->setTop(pStack->getTop() - 1);
    *pData = http://www.mamicode.com/pStack->getData(pStack->getTop());

    return STACK_OK;
}

int STACK::IsEmpty(STACK *pStack) {
    if (!pStack)
        return STACK_ERR;

    if (0 != pStack->getTop())
        return STACK_EMPTY;

    return STACK_OK;
}

 

main.cpp

#include "STACK/STACK.h"
#include <stdlib.h>
#include <iostream>
using namespace std;

void function() {
    STACK *pStack = new STACK;
    int *data = http://www.mamicode.com/new int[5];
    int pdata;
    int i;
    for (i = 4; i >= 0; i--) {
        data[i] = i;
    }
    for (i = 5; i >= 0; i--) {
        pStack->Push(pStack, i);
        cout << i << "  ";
    }
    cout << endl;
    for (i = 5; i >= 0; i--) {
        pStack->Pop(pStack, &pdata);
        cout << pdata << " ";
    }
    cout << endl;
    pStack->Push(pStack, 9);
    pStack->Pop(pStack, &pdata);
    cout << pdata << " ";
    pStack->Push(pStack, 5);
    pStack->Push(pStack, 3);
    pStack->Push(pStack, 7);
    pStack->Pop(pStack, &pdata);
    cout << pdata << " ";
    pStack->Push(pStack, 0);
    pStack->Pop(pStack, &pdata);
    cout << pdata << " ";
    pStack->Pop(pStack, &pdata);
    cout << pdata << " ";
    pStack->Pop(pStack, &pdata);
    cout << pdata << " " << endl;
    delete pStack;
}

int main() {
    function();
    return 0;
}

 

C++__顺序栈(练习)