Q:通過 數組 實現 棧 功能
A:
MyStack.h
#ifndef MYSTACK_H#define MYSTACK_H/******************************//*棧實現 2017.03.02 by hyc*****//******************************/class MyStack{public: MyStack(int size); //初始化??臻g ~MyStack();//回收??臻g內存 void clearStack();//清空棧 bool stackEmpty();//判空棧,若空返回true bool stackFull();//判滿棧,若滿返回true int stackLength();//棧中元素個數 bool push(char elem);//元素入棧,棧頂上升 bool pop(char &elem);//元素出棧,棧頂下降 void stackTraverse(bool isFromBottom);//遍歷棧中元素 isFromBottom=1,從棧底遍歷PRivate: char *m_pBuffer;//??臻g指針 int m_isize;//棧容量 int m_itop;//棧頂,也是棧中元素個數};#endif // !MYSTACK_HMyStack.cpp
#include "MyStack.h"#include <iostream>using namespace std;MyStack::MyStack(int size){ m_isize = size; m_pBuffer = new char[size]; m_itop = 0;}MyStack::~MyStack(){ delete[] m_pBuffer;}void MyStack::clearStack(){ m_itop = 0;}bool MyStack::stackEmpty(){ return 0 == m_itop ? true : false;}bool MyStack::stackFull(){ return m_isize == m_itop ? true : false;}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] << ","; } }}demo.cpp:用于測試棧功能實現情況#include "MyStack.h"#include <iostream>using namespace std;/******************************//*棧實現 2017.03.02 by hyc*****//******************************/int main(void){ MyStack *pStack = new MyStack(5); pStack->push('h');//棧底 pStack->push('e'); pStack->push('l'); pStack->push('l'); pStack->push('o');//棧頂 if (pStack->stackFull()){ cout << "棧滿" << endl; } pStack->stackTraverse(true); cout << endl; char ch; pStack->pop(ch); cout << ch << endl; if (pStack->stackEmpty()){ cout << "???quot; << endl; } if (pStack->stackFull()){ cout << "棧滿" << endl; } pStack->stackTraverse(false); cout << pStack->stackLength() << endl; pStack->clearStack(); if (pStack->stackEmpty()){ cout << "???quot; << endl; } delete pStack; pStack = NULL; system("pause"); return 0;}輸出結果:
注意:本次練習只實現了簡單的int類型的棧功能,可以使用模板類進一步實現其多類型支持。并且本程序有很多不完善的地方,如分配空間等的異常檢測。
新聞熱點
疑難解答
圖片精選