C++栈类的实现

2025-02-28 15:35:47
推荐回答(2个)
回答1:

我昨天做了一个基本符合要求:(定义在Stack.h 头文件中)#ifndef stack_h
#define stack_h
#include
using namespace std;
typedef char Stack_entry;//定义数组类型,你可以改成int 或者其他的
const int stackmax = 20;
enum Error_code{success,underflow,overflow};//系统返回值,后面能用到
class Stack
{
private:
int count;
Stack_entry entry [stackmax];
public :
Stack();
bool const empty();
Error_code pop();
Error_code top(Stack_entry &temp) const;
Error_code push(const Stack_entry &temp);
};Stack::Stack()
{
count=0;
}bool const Stack::empty()
{
if(count == 0)
return false ;
else
return true;
}Error_code Stack::pop()
{
Error_code outcome = success;
if(count==0)
outcome = success;
else
count--;
return outcome;
}Error_code Stack::push(const Stack_entry &temp)
{
Error_code outcome = success;
if(count==stackmax)
outcome = overflow;
else
entry[count++]=temp;
return outcome;
}Error_code Stack::top(Stack_entry &temp) const
{
Error_code outcome = success;
if(count==0)
outcome = underflow;
else
temp = entry[count-1];
return outcome;
}#endif

回答2:

可以用类来实现的啊给你个思路class 栈public 出栈操作 进栈操作private 数据数组 flag其中数据数组就是一个数组,flag用来标记当前元素,初始状态为0表示栈里面没有元素出栈操作:读出 数组[flag],flag-=1;进栈操作:flag+=1 读入 数组[flag]