C++编程练习(3)----“实现简单的栈的顺序存储结构“

栈(stack)是限定仅在表尾进行插入和删除操作的线性表。

允许插入和删除的一端称为栈顶(top),另一端称为栈底(bottom)。

栈又称为后进先出(Last In First Out)的线性表,简称为LIFO结构。


用数组方式实现简单的栈的代码如下:

/* SqStack.h*/
#include<iostream>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXSIZE 20
typedef int SElemType;
typedef int Status;

class SqStack{
public:
	SqStack():data(),top(-1) {};
	SElemType data[MAXSIZE];
	int top;	/*用于栈顶指针*/
	Status Push(SElemType e);	/*进栈操作*/
	Status Pop(SElemType *e);	/*出栈操作*/
	Status ShowStack() const;	/*从栈顶至栈底输出元素*/
};
Status SqStack::Push(SElemType e)
{
	if(top==MAXSIZE-1)	/*栈满*/
		return ERROR;
	top++;
	data[top]=e;
	return OK;
}
Status SqStack::Pop(SElemType *e)
{
	if(top==-1)
		return ERROR;
	*e=data[top];
	top--;
	return OK;	
}
Status SqStack::ShowStack() const
{
	int j;
	std::cout<<"从栈顶至栈底输出元素为:";
	for(j=top;j>=0;j--)
		std::cout<<data[j]<<"  ";
	std::cout<<std::endl;
	return OK;
}



原文地址:https://www.cnblogs.com/fengty90/p/3768860.html