#include <iostream>
using namespace std;
#define MAXSIZE 100;
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(bool isfrombottom);
private:
char *m_pBuffer;
int m_iSize;
int m_iTop;
};
MyStack::MyStack(int size)
{
m_iSize=size;
m_pBuffer=new char[size];
m_iTop=0;
}
MyStack::~MyStack()
{
delete []m_pBuffer;
}
bool MyStack::stackEmpty()
{
if(m_iTop==0)
{
return true;
}
return false;
}
bool MyStack::stackFull()
{
if(m_iTop==m_iSize)
{
return true;
}
return false;
}
void MyStack::clearStack()
{
m_iTop=0;
}
int MyStack::stackLength()
{
return m_iTop;
}
bool MyStack::push(char elem)
{
if(stackFull())
{
return false;
}
m_pBuffer[m_iTop]=elem;
m_iTop++;
return true;
}
bool MyStack::pop(char &elem)
{
if(stackEmpty())
{
return false;
}
m_iTop--;
elem=m_pBuffer[m_iTop];
return true;
}
void MyStack::stackTraverse(bool isfrombottom)
{
if(isfrombottom)
{
for(int i=0;i<m_iTop;i++)
{
cout<<m_pBuffer[i]<<",";
}
}
else
{
for(int i=m_iTop-1;i>=0;i--)
{
cout<<m_pBuffer[i]<<",";
}
}
}
int main()
{
MyStack *pStack=new MyStack(5);
pStack->push('h');//底
pStack->push('e');
pStack->push('l');
pStack->push('l');
pStack->push('o');//顶
pStack->stackTraverse(true);
cout<<endl;
char elem=0;
pStack->pop(elem);
cout<<elem<<endl;
// pStack->clearStack();
cout<<pStack->stackLength()<<endl;
pStack->stackTraverse(false);
if(pStack->stackEmpty())
{
cout<<"栈为空"<<endl;
}
if(pStack->stackFull())
{
cout<<"栈为满"<<endl;
}
delete pStack;
pStack=NULL;
return 0;
}
栈
最新推荐文章于 2024-07-14 09:49:31 发布