栈的基本算法的实现:
MyStack.h
class MyStack
{
public:
MyStack(int size); //分配内存初始化栈空间,设定栈容量,栈顶
~MyStack(); //回收栈空间内存
bool stackEmpty(); //判定栈是否为空
bool stackFull(); //判定栈是否满
void clearStack();//清空栈
int stackLength();//已有元素的个数
bool push(char elem); //元素入栈,栈顶上升
bool pop(char *elem); //元素出栈,栈顶下降
void stackTraverse();//遍历栈中所有元素
private:
int m_iTop; //栈顶
int m_iSize; //栈的空间长度
char *m_pBuffer; //栈空间
};
MyStack.cpp
#include"MyStack.h"
#include<iostream>
using namespace std;
MyStack::MyStack(int size)
{
m_iSize=size;
m_pBuffer=new char[m_iSize];
m_iTop=0;
}
MyStack::~MyStack()
{
delete []m_pBuffer;
}
bool MyStack::stackEmpty()
{
if(m_iTop==0)
{
cout<<"栈为空"<<endl;
return true;
}
else
return false;
}
bool MyStack::stackFull()
{
if(m_iTop>=m_iSize)
{
return true;
}
else
return false;
}
void MyStack::clearStack()
{
m_iTop=0;
}
int MyStack::stackLength()
{
return m_iTop;
}
bool MyStack::push(char elem)
{
if(stackFull())
{
cout<<"栈已满,无法压入"<<endl;
return false;
}
else
{
m_pBuffer[m_iTop]=elem;
m_iTop++;
return true;
}
}
bool MyStack::pop(char *elem)
{
if(stackEmpty())
{
cout<<"栈为空,无法推出"<<endl;
return false;
}
else
{
m_iTop--;
*elem=m_pBuffer[m_iTop];
return true;
}
}
void MyStack::stackTraverse()
{
for(int i=0;i<m_iTop;i++)
{
cout<<m_pBuffer[i]<<" ";
}
cout<<endl;
}
main.cpp
#include<iostream>
#include<stdlib.h>
#include"MyStack.h"
using namespace std;
void main()
{
MyStack *stack=new MyStack(5);
char temp=' ';
stack->push('a');
stack->push('b');
stack->push('c');
stack->push('d');
stack->push('e');
stack->push('f');
stack->stackTraverse();
cout<<"栈的长度:"<<stack->stackLength()<<endl;
stack->pop(&temp);
cout<<"第一个出栈元素:"<<temp<<endl;
stack->pop(&temp);
cout<<"第二个出栈元素:"<<temp<<endl;
stack->pop(&temp);
cout<<"第三个出栈元素:"<<temp<<endl;
stack->pop(&temp);
cout<<"第四个出栈元素:"<<temp<<endl;
stack->pop(&temp);
cout<<"第五个出栈元素:"<<temp<<endl;
stack->pop(&temp);
cout<<"第六个出栈元素:"<<temp<<endl;
system("pause");
}
运行结果如下: