具体实现代码@数据结构探险—栈篇 2-4
有需要的自取。
file:MyStack.hpp
#ifndef MyStack_hpp
#define MyStack_hpp
#include <stdio.h>
class MyStack{
public:
MyStack(int size);
~MyStack();
bool stackFull();
bool stackEmpty();
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;
};
#endif /* MyStack_hpp */
file:MyStack.cpp
#include "MyStack.hpp"
#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;
m_pBuffer = NULL;
}
bool MyStack::stackFull(){
return m_iTop==m_iSize?true:false;
}
bool MyStack::stackEmpty(){
return m_iTop==0?true:false;
}
void MyStack::clearStack(){
m_iTop = 0;
}
int MyStack::stackLength(){
return m_iTop;
}
bool MyStack::push(char elem){
if(stackFull()){
return false;
}
else{
m_pBuffer[m_iTop] = elem;
m_iTop++;
return true;
}
}
bool MyStack::pop(char &elem){
if(stackEmpty()){
return false;
}
else{
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] << endl;
}
}
else{
for(int i = m_iTop-1;i >=0;i--){
cout << m_pBuffer[i] << endl;
}
}
}
file demo.cpp
#include <iostream>
#include <string>
#include "MyStack.hpp"
using namespace std;
int main(void){
MyStack *pStack = new MyStack(5);
pStack->push('a');
pStack->push('e');
pStack->push('i');
pStack->push('o');
pStack->push('u');
pStack->stackTraverse(true);
char elem = 0;
pStack->pop(elem);
cout << elem << endl;
cout << pStack->stackLength() << endl;
pStack->stackTraverse(true);
pStack->clearStack();
if(pStack->stackEmpty()){
cout << "栈为空" << endl;
}
if(pStack->stackFull()){
cout << "栈为满" << endl;
}
delete pStack;
pStack = NULL;
}
点击查看更多内容
2人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦