栈数据结构的实现(合肥工业大学(胡学钢版)) (有改动)

暑假复习数据结构,不足之处多多指正

1th:

#include<iostream>
#define MaxSize 50
typedef int DataType;
using namespace std;

class stack
{
public:
    stack();
    bool isempty() const;
    bool isfull() const;
    void pop();
    void push(const DataType x);
    DataType get_top();
private:
    int count;
    DataType data[MaxSize];
};

stack::stack()
{
    count = 0;
}

bool stack::isempty() const
{
    if(0==count)
    return true;
    return false;
}

bool stack::isfull() const
{
    if(MaxSize==count)
    return true;
    return false;
}

void stack::pop()
{
    if(isempty())
    cout<<"underflow \n";
    count--;
}

void stack::push(const DataType x)
{
    if(isfull())
    cout<<"overflow \n";
    data[count]=x;
    count++;
}

DataType stack::get_top()
{
    if(isempty())
    cout<<"underflow \n";
    return data[count-1];
}

测试代码:


main()          //测试代码 
{
    //初始化1,2,3,4,5 
    stack s;
    s.push(1);
    s.push(2);
    s.push(3);    
    s.push(4);    
    s.push(5);
    cout<<"现在栈顶是:"<<s.get_top() <<endl;
    s.pop();       //出栈一个元素
    cout<<"出栈之后栈顶是:"<<s.get_top() <<endl; 
}

运行截图:

猜你喜欢

转载自blog.csdn.net/Drifter_Galaxy/article/details/81202517