堆栈作业1:实现顺序栈(字符型数据为例)

280 阅读1分钟
#include<cstdio>
#include<cstring>
#include<algorithm>
#include <iostream>
using namespace std;
//堆栈类
const int Max = 100;
class Stack//栈类的定义(字符型数据为例)
{
private:
    char* date;//数据域
    int size;//堆栈的实际大小
    int top;//栈顶

public:
    Stack();//构造函数
    Stack(int s);//有参构造函数
    ~Stack();//析构函数
    void push(char ch);//成员函数:入栈
    char pop();//成员函数: 出栈并返回栈顶元素
    char getTop();//成员函数: 获得栈顶元素
    bool isEmpty();//成员函数:栈是否为空
    bool isFull(); //成员函数:栈是否满
    void setNull();//设置栈为空
};
//构造函数
Stack::Stack()
{
    size = Max;
    top = -1;
    date = new char[Max]; //缺省构造函数分配最大空间;
}
Stack::Stack(int s)
{
    size = s;
    top = -1;
    date = new char[size];//根据指定大小分配栈的空间
}
Stack::~Stack()
{
    delete[] date;//一定要记得内存回收
}
//成员函数
void Stack::push(char ch)
{
    //实现单一功能,不要有输入输出等别的功能
    if (!isFull())
    {
        date[++top] = ch;
    }
}
char Stack::pop()
{
    if (!isEmpty())
    {
        return date[top--];
    }
}
char Stack::getTop()
{
    if (!isEmpty())
    {
        return date[top];
    }
}
bool Stack::isEmpty()
{
    if (top == -1)
    {
        return true;
    }
    else
    {
        return false;
    }
}
bool Stack::isFull()
{
    if (top +1 == size)
    {
        return true;
    }
    else
    {
        return false;
    }
}
void Stack::setNull()
{
    top = -1;
}
int main()
{
    //测试
    Stack s1(2);
    s1.push('a');
    s1.push('b');
    cout << s1.isFull() << endl;
    cout << s1.getTop() << endl;
    cout << s1.pop() << endl;
    cout << s1.pop() << endl;
    cout << s1.isEmpty() << endl;
}