c++实现基本栈操作:后进先出
头文件:(注意是ifndef)
#ifndef MYSTACK_H
#define MYSTACK_H
class MyStack{
public:
MyStack(int size); //分配内存初始化栈空间,设定栈容量,栈顶
~MyStack(); //回收空间
bool stackFull(); //判定栈满
bool stackEmpty(); //判定栈空
void clear(); //清空栈
int stackLength(); //栈中元素个数
void push(char elem); //元素入栈,栈顶上升
char pop(); //元素出栈,栈顶下降
void stackTraverse(bool isFromBottom); //遍历栈
private:
char *m_pBuffer; //栈空间指针
int m_size; //栈大小
int m_top; //栈顶
};
#endif
关键代码及实现:
#include <iostream>
#include "MyStack.h"
using namespace std;
MyStack::MyStack(int size){
m_size=size;
m_pBuffer=new char[m_size];
m_top=0;
}
MyStack::~MyStack(){
delete []m_pBuffer;
}
int MyStack::stackLength(){
return m_size;
}
bool MyStack::stackEmpty(){
if (0==m_top)
{
return true;
}
return false;
}
bool MyStack::stackFull(){
if (m_top==m_size)
{
return true;
}
return false;
}
void MyStack::clear(){
m_top=0;
}
void MyStack::push(char elem){
if (stackFull())
{
}
m_pBuffer[m_top]=elem;
m_top++;
}
char MyStack::pop(){
if (stackEmpty())
{
throw 1;
}
m_top--;
return m_pBuffer[m_top];
}
void MyStack::stackTraverse(bool isFromBottom){
if (isFromBottom)
{
for (int i=0;i<m_top;i++)
{
cout<<m_pBuffer[i]<<" ";
}
}else
for(int i=m_top-1;i>=0;i--){
cout<<m_pBuffer[i]<<" ";
}
}
int main(){
MyStack *p=new MyStack(5);
p->push('i');
p->push('k');
p->push('o');
p->push('b');
p->push('e');
p->stackTraverse(true);
cout<<endl;
p->stackTraverse(false);
cout<<endl;
if (p->stackEmpty())
{
cout<<"栈为空"<<endl;
}
if (p->stackFull())
{
cout<<"栈为满"<<endl;
}
cout<<"出栈元素:"<<p->pop()<<endl;
cout<<"出栈元素:"<<p->pop()<<endl;
p->stackTraverse(true);
return 0;
}
实现结果: