**
**
1.实现进制转换 转换原则: 源码:
#define BINARY 2 #define OCTONARY 8 #define HEXADECIMAL 16 char num[] = "0123456789ABCDEF"; StackTest<int> *m = new StackTest<int>(10); int N = 2017; int mod = 0; while(N != 0){ mod = N % 16; m->Push(mod); N = N/16; } int element =0; while (!m->StackEmpty()) { m->Pop(element); cout << num[element]; }2.实现字符匹配
StackTest<char> *m = new StackTest<char>(10); StackTest<char> *c = new StackTest<char>(10); char str[] = "[()]]"; char need = 0; for(int i=0; i<strlen(str); i++){ if(str[i] != need){ m->Push(str[i]); switch (str[i]) { case '[': if(need != 0){ c->Push(need); } need = ']'; break; case '(': if(need != 0){ c->Push(need); } need = ')'; break; default: cout << "not match" << endl; return a.exec(); } }else{ char element; m->Pop(element); if(c->Pop(need)){ need = 0; } } } if(m->StackEmpty()){ cout << "match right" << endl; }else{ cout << "not match" << endl; } delete m; m=nullptr; delete c; c=nullptr; return a.exec();3.栈示例源码
#ifndef STACKTEST_H #define STACKTEST_H #include<iostream> using namespace std; template<typename T> class StackTest { public: StackTest(int size); ~StackTest(); bool StackEmpty() const; bool StackFull() const; void ClearStack(); int StackLenth(); bool Push(T element); bool Pop(T& element); void PrintSelf(); private: T* m_pBuffer; int m_iSize; int m_iLength; }; template<typename T> StackTest<T>::StackTest(int size) { m_iSize = size; m_pBuffer = new T[m_iSize]; m_iLength = 0; } template<typename T> StackTest<T>::~StackTest() { delete[] m_pBuffer; m_pBuffer = nullptr; } template<typename T> bool StackTest<T>::StackEmpty() const { return 0==m_iLength ? true : false; } template<typename T> bool StackTest<T>::StackFull() const { return m_iLength==m_iSize ? true : false; } template<typename T> void StackTest<T>::ClearStack() { m_iLength = 0; } template<typename T> int StackTest<T>::StackLenth() { return m_iLength; } template<typename T> bool StackTest<T>::Push(T element) { if(StackFull()) return false; m_pBuffer[m_iLength] = element; ++m_iLength; return true; } template<typename T> bool StackTest<T>::Pop(T &element) { if(StackEmpty()) return false; element = m_pBuffer[m_iLength-1]; --m_iLength; return true; } template<typename T> void StackTest<T>::PrintSelf() { cout << "up to down:"; for(int i=0; i<m_iLength; i++){ cout << m_pBuffer[i]; } cout << endl; cout << "down to up:"; for(int i=m_iLength-1; i>=0; i--){ cout << m_pBuffer[i]; } cout << endl; } #endif // STACKTEST_H