标签:
参考链接:数据结构探险—栈篇
学了队列之后,栈就很简单了,换汤不换药。
课程笔记:
//MyStack.h #pragma once 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(); private: char *m_pBuffer; int m_iSize; int m_iTop; };
//MyStack.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; } bool MyStack::stackEmpty() { if (0 == m_iTop) { 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() { for (int i = 0; i < m_iTop; i++) { cout << m_pBuffer[i] << ","; } }
//demo.cpp #include<iostream> #include"MyStack.h" using namespace std; int main() { MyStack *p = new MyStack(5); p->push(‘h‘); p->push(‘e‘); p->push(‘l‘); p->push(‘i‘); p->push(‘z‘); p->stackTraverse(); char tmp = 0; p->pop(tmp); cout << endl << "ding is " << tmp << endl; p->clearStack(); cout << p->stackLength() << endl; if (p->stackEmpty()) { cout << "stack is empty" << endl; } if (p->stackFull()) { cout << "stack is full" << endl; } delete p; p = nullptr; return 0; }
标签:
原文地址:http://www.cnblogs.com/leezx/p/5801055.html