栈
#pragma once
class MyStack
{
public:
MyStack(int size); //分配内存初始化栈空间,设定栈容量,栈顶
~MyStack(); //回收栈空间内存
bool stackEmpty(); //判定栈是否为空,为空返回true,非空返回false
bool stackFull(); //判定栈是否已满,为满返回true,不满返回false
void clearStack(); //清空栈
int stackLength(); //已有元素的个数
bool push(char elem); //元素入栈,栈顶上升
bool pop(char &elem); //元素出栈,栈顶下降
void stackTraverse(bool isFromButtom); //遍历栈中所有元素
private:
char *m_pBuffer; //栈空间指针
int m_iSize; //栈容量
int m_iTop; //栈顶,栈中元素个数
};
#include <iostream>
#include "MyStack.h"
using namespace std;
//分配内存初始化栈空间,设定栈容量,栈顶
MyStack::MyStack(int size)
{
m_iSize = size; //栈容量
m_pBuffer = new char[m_iSize]; //动态申请内存
m_iTop = 0; //栈顶置为0
}
MyStack::~MyStack()
{
delete[]m_pBuffer; //释放内存
}
//判定栈是否为空,为空返回true,非空返回false
bool MyStack::stackEmpty()
{
//写成这种形式可以防止代码写成=,写成=会报错
if (0 == m_iTop) //if(m_iTop == 0)
{
return true;
}
return false;
}
//判定栈是否已满,为满返回true,不满返回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;
}
/*
char MyStack::pop()
{
if(stackEmpty())
{
throw 1;
}
else
{
m_iTop--;
return m_pBuffer[m_iTop];
}
}
*/
//元素出栈,栈顶下降
bool MyStack::pop(char &elem)
{
//判断栈是否空,空直接返回
if (stackEmpty())
{
return false;
}
//栈顶--(注意入栈的时候栈顶++指向的是一个空位置,故先--)
m_iTop--;
//直接取出
elem = m_pBuffer[m_iTop];
return true;
}
//遍历栈中所有元素
void MyStack::stackTraverse(bool isFromButtom)
{
if (isFromButtom)
{
//从栈底向栈顶遍历
for (int i = 0; i < m_iTop; i++)
{
cout << m_pBuffer[i] << ",";
}
}
else
{
//从栈顶向栈底遍历,同样因为入栈时栈顶++,故栈顶-1的位置才实际有值
for (int i = m_iTop - 1; i >= 0; i--)
{
cout << m_pBuffer[i] << ",";
}
}
}
#include <iostream>
#include "stdlib.h"
#include "MyStack.h"
using namespace std;
int main(void)
{
MyStack *pStack = new MyStack(5);
pStack->push('h'); //底
pStack->push('e');
pStack->push('l');
pStack->push('l');
pStack->push('o'); //顶
//遍历(栈底到栈顶)
pStack->stackTraverse(true);
char elem = 0;
//出栈
pStack->pop(elem);
cout << endl;
cout << elem << endl;
//pStack->clearStack();
//遍历(栈顶到栈底)
pStack->stackTraverse(false);
//输出栈内元素个数
cout << pStack->stackLength() << endl;
if (pStack->stackEmpty())
{
cout << "栈为空" << endl;
}
if (pStack->stackFull())
{
cout << "栈为满" << endl;
}
delete pStack;
pStack = NULL;
system("pause");
return 0;
}