实现stack功能

class CStack
{
public:
    CStack();//建立一个10个元素的栈
    CStack(int s);//建立一个具有 s个元素的栈
    CStack(CStack &r_s);//注意,没有重载赋值操作符
    int get(int index);//返回下标为index 的栈元素
    void push(int n);//进栈,top加1,把n的值存入栈顶
    int isEmpty();//判断栈是否为空,空则返回1,否则返回0
    int isFull();//判断栈是否是满的,空则返回1,否则返回0
    int pop();//出栈,返回栈顶元素,top减1
    ~CStack();//析构函数,释放在构造时申请的空间
private:
    int *a;
    int size;//栈的大小
    int top;//指向栈顶
};
#include <iostream>
using namespace std;
void PopAll(CStack &stack)
{
    while (!stack.isEmpty())
        cout << stack.pop() << " ";
    cout << endl;
}
 
CStack::CStack() :size(10), top(-1)
{
    cout << "Constructor" << endl;
    a = new int[size];
}
CStack::CStack(int s) : size(s), top(-1)
{
    cout << "Constructor" << endl;
    a = new int[size];
}
CStack::CStack(CStack &r_s) : size(r_s.size), top(r_s.top)
{
    cout << "copy Constructor" << endl;
    a = new int[size];
    memcpy(a, r_s.a, size * sizeof(int));
}
CStack::~CStack(){  PopAll(*this);cout << "Distructor" << endl; delete[] a; }
int CStack::get(int index){
    if (index >= 0 && index < top)
        return a[index];
    else return -1;//-1作为返回错误?还是抛出异常?
}
void CStack::push(int n){
    if (!isFull())
        a[++top] = n;
}
int CStack::pop(){
    if (!isEmpty())
        return a[top--];
}
int CStack::isEmpty(){
    if (-1 == top) return 1;
    else return 0;
}
int CStack::isFull(){
    if (top + 1 == size) return 1;
    else return 0;
}
 
 
#include <iostream>
using namespace std;
 
void GetNDataToStack(CStack &stack, unsigned int n)
{
    while (n--)
    {
        int DataGet;
        cin >> DataGet;
        stack.push(DataGet);
    }
}
 
int main()
{
    int nLoop;
    cout << "输入要构造几组数据:";
    cin >> nLoop;
    for (int index = 0; index < nLoop; ++index)
    {
        cout <<"输入要多少个数据存储:";
        unsigned int nDataCount;
        cin >> nDataCount;
        CStack stack(nDataCount);
        GetNDataToStack(stack, nDataCount);
    }
 
    return 0;
}

  

原文地址:https://www.cnblogs.com/zhaodun/p/6772923.html