编写一个类,实现简单的栈。栈中有以下操作:元素入栈,读出栈顶元素值,退栈,判断栈顶空否。如果栈溢出,程序终止。栈的数据成员由10个整形的数构成。先后作出如下操作:
创建栈:
将10入栈;
将12入栈;
将14入栈;
读出并输入栈顶元素;
退栈;
读出并输出栈顶元素。
參考答案:class CStack
{
protected:
int *pStack;
int data[10];
public:
CStack();
virtual ~CStack();
int GetStack(int *n);
int SetStack(int n);
};
int main(int argc, char* argv[])
{
CStack m_Stack;
m_Stack.SetStack(10);
m_Stack.SetStack(12);
m_Stack.SetStack(14);
int x;
if(!m_Stack.GetStack(&x))printf("No Data!\n");
printf("%d\n",x);
if(!m_Stack.GetStack(&x))printf("No Data!\n");
printf("%d\n",x);
if(!m_Stack.GetStack(&x))printf("No Data!\n");
printf("%d\n",x);
if(!m_Stack.GetStack(&x))printf("No Data!\n");
return 0;
}
int CStack::GetStack(int *n)
{
if( pStack == data )return 0;
pStack--;
*n = *pStack;
return 1;
}
int CStack::SetStack(int n)
{
if( pStack == (data+10) )return 0;
*pStack = n;
pStack++;
return 1;
}
CStack::CStack()
{
pStack = data;
}
CStack::~CStack()
{
}