求个C++栈的简单程序

来源:百度知道 编辑:UC知道 时间:2024/05/31 15:27:13
要能说明栈的使用方法

#include <iostream>

using namespace std;

// 栈容量为100个单元
#define MAX_LVL 100

class stack
{
int m_stack[MAX_LVL]; // 栈存储缓冲区
int m_index; // 栈序号
public:
stack(); // 初始化栈存储缓冲区和序号
bool push(int number); // 压栈,或者数值进栈
bool pop(int &number); // 退栈,或者数值出栈
};

stack::stack()
{
m_index = 0;
memset(m_stack, 0, sizeof(m_stack));
}

bool stack::push(int number)
{
if (m_index >= MAX_LVL)
{
cout << "stack is overflow\n";
return false;
}
m_stack[m_index++] = number; //压栈后,栈序号增一
return true;
}

bool stack::pop(int &number)
{
if (m_index <= 0)
{
cout << "stack is underflow\n";
return false;
}
number = m_stack[--m_index]; // 退栈后,栈序号减一
return true;
}

// 主程序功能是读入整型数值,如果