当先锋百科网

首页 1 2 3 4 5 6 7
#include<iostream>
using namespace std;

#define DataType int
#define MaxSize 5                    //栈容量
typedef class
{
    DataType stack_data[MaxSize];
    int top=-1;                      //顺序栈只需要int型指示栈顶的位置下标
    public:
    void push(DataType data); 
    DataType pop();
    bool empty();
    int length();
    DataType gettop();              
}stack;

void stack::push(DataType data)
{
    if(stack::top==MaxSize-1)       //判断栈是否满了
    {
        cout<<"入栈失败(栈满)!"<<endl;
    }
    else
    {
        stack::stack_data[++stack::top]=data;   
        cout<<data<<" 入栈."<<endl;
    }
}

DataType stack::pop()
{
    if(stack::top==-1)             //判断栈是否为空
    {
        cout<<"出栈失败(栈空!)"<<endl;
        return -1;
    }
    DataType top_data = stack::stack_data[stack::top--];
    cout<<top_data<<" 出栈."<<endl;
    return top_data;
}
//根据栈顶位置判断栈是否为空
bool stack::empty()
{
    if(stack::top == -1)
    {
        cout<<"栈检查:空!"<<endl;
        return true;
    }
    cout<<"栈检查:非空!"<<endl;
    return false;    
}

int stack::length()
{
    cout<<"栈检查:数据个数为"<<stack::top+1<<endl;
    return stack::top+1;
}

DataType stack::gettop()
{
    if(stack::top==-1)
    {
        cout<<"读取栈顶元素失败(栈空!)"<<endl;
        return -1;
    }
    DataType top_num = stack::stack_data[stack::top];
    cout<<"栈顶元素为:"<<top_num<<endl;
    return top_num;
}
//测试
int main()
{
    stack s1;
    s1.push(1);
    s1.push(2);
    s1.push(3);
    s1.push(4);
    s1.push(5);
    s1.push(6);
    s1.length();
    s1.pop();
    s1.pop();
    s1.pop();
    s1.gettop();
    s1.pop();
    s1.pop();
    s1.pop();
    s1.empty();
}


运行结果:

附:栈之链式栈 C++代码实验