数据结构--栈--顺序栈/链式栈(附: 字符括号合法配对检测)
生活随笔
收集整理的這篇文章主要介紹了
数据结构--栈--顺序栈/链式栈(附: 字符括号合法配对检测)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
棧結構:先進后出,后進先出,像疊盤子一樣,先疊的后用。
代碼github地址 https://github.com/hitskyer/course/tree/master/dataAlgorithm/chenmingming/stack
1.順序棧(數組存儲,需給定數組大小,到達容量需要copy轉移數據)
1.1 頭文件 arrStack.h
// // Created by mingm on 2019/3/27. // #ifndef STACK_ARRSTACK_H #define STACK_ARRSTACK_H typedef unsigned int UINT; template <class T> class arrStack { public:arrStack(int capacity); // 初始化棧~arrStack(void); // 析構棧bool Empty() const; // 判斷是否為空bool IsFull() const; //判斷棧是否滿了void Clear(); // 則清空棧T& GetTop() const; // 得到棧頂元素UINT GetLength() const; // 返回棧的長度void Push(T &data); //往棧中壓入數據void Expand(); //棧擴容void Pop(); //將棧頂數據彈出void print(); //自己加的接口,打印輸出stack內容 private:int m_pTop; // 棧頂指針UINT m_nStackLen; // 棧容量T* arr; //數組arr };#endif //STACK_ARRSTACK_H1.2 類實現文件 arrStack.cpp
// // Created by mingm on 2019/3/27. // #include "arrStack.h" #include <iostream> using namespace std; template <class T> arrStack<T>::arrStack(int capacity):m_pTop(-1),m_nStackLen(capacity) {arr = new T[capacity]; } template <class T> arrStack<T>::~arrStack() {Clear();delete [] arr;arr = NULL; } template <class T> bool arrStack<T>::Empty() const {return m_pTop == -1; } template <class T> bool arrStack<T>::IsFull() const {return m_pTop == m_nStackLen - 1; } template <class T> void arrStack<T>::Clear() {m_pTop = -1; } template <class T> void arrStack<T>::Push(T &data) {if(IsFull()){ // cout << "overflow !" << endl;Expand();}arr[++m_pTop] = data; } template <class T> void arrStack<T>::Expand() {m_nStackLen = 2 * m_nStackLen;T* temparr = new T[m_nStackLen];for(int i = 0; i <= m_pTop; ++i){temparr[i] = arr[i];}T* temp = arr;arr = temparr;temparr = temp;delete [] temparr;temparr = NULL; } template <class T> void arrStack<T>::Pop() {if(!Empty())--m_pTop; } template <class T> T& arrStack<T>::GetTop() const {if(!Empty())return arr[m_pTop];throw "no elem!"; //拋出異常 } template <class T> UINT arrStack<T>::GetLength() const {return m_nStackLen; } template <class T> void arrStack<T>::print() {cout << "----arrstack top----" << endl;int i = m_pTop, j = m_pTop;while(m_pTop != -1 && j >= 0){cout << "No." << i-- << " elem " << arr[j--] << endl;}cout << "----arrstack bottom----" << endl; }1.3 測試程序及括號格式合法性檢測 arrstack_testMain.cpp(練習了下try,catch)
// // Created by mingm on 2019/3/27. // #include "arrStack.cpp" #include <string> #include <iostream> using namespace std; int main() {for(int i = 0; i < 20; ++i){int k = 0;arrStack<int> int_arr_stack(8);int_arr_stack.print();cout << "the capacity of stack is " << int_arr_stack.GetLength() << endl;while(k < i){int_arr_stack.Push(k);++k;}try{cout << "top elem is " << int_arr_stack.GetTop() << endl;}catch(const char* str){cout << str << endl;}cout << "the capacity of stack is " << int_arr_stack.GetLength() << endl;int_arr_stack.print();int_arr_stack.Clear();cout << "---------------------------------" << endl;}cout << "以下測試一個字符串是否有非法格式的括號" << endl;char conti = 'y', str;while(conti == 'y'|| conti == 'Y'){bool legal = true;arrStack<char> charstack(100);cout << "please enter a string to check its brackets legal or not !" << endl;while(cin.get(str) && str != '\n') //不斷地獲取輸入的字符{if(str == '{' || str == '[' || str == '(') //遇到左括號不斷地壓棧{charstack.Push(str);continue;}switch(str) //遇到非左括號{case '}':try{if(charstack.GetTop() && charstack.GetTop() == '{') //棧不為空且棧頂與右括號匹配charstack.Pop(); //刪除左括號elselegal = false; //直接遇上右括號,非法;or 棧頂與當前右括號不匹配}catch(const char* str) //若捕獲try內的異常,沒有元素在棧內,則遇到右括號,非法{legal = false;}break;case ']':try{if(charstack.GetTop() && charstack.GetTop() == '[')charstack.Pop();elselegal = false;}catch(const char* str){legal = false;}break;case ')':try{if(charstack.GetTop() && charstack.GetTop() == '(')charstack.Pop();elselegal = false;}catch(const char* str){legal = false;}break;default:break;}if(!legal)break; //如果非法,不必循環了,直接退出}if(legal && charstack.Empty()) //如果合法,且符號都匹配了(棧為空)cout << "legal string !" << endl;else{cout << "illegal string !" << endl;cin.ignore(10000,'\n'); //清除非法字符后面尚未get的字符}cout << "continue? y/n: " ;cin >> conti;cin.get();}return 0; }2.鏈式棧(鏈表存儲,無需給定長度)
2.1 頭文件 stack.h
/* * 概述: 棧 * 作者: dongyaxing * 版本: 1.0 * 創建時間:2019/3/25 20:47 * 修改者: liuyanfu * 修改時間: 2019/3/25 21:14 */ #ifndef _STACK_H #define _STACK_H template <class T> struct SNode {T data;SNode *pNext; }; template <class T>using StackNode = SNode<T>* ; //某些編譯器不支持改語法 //template <class T> typedef SNode<T>* StackNode; //錯誤寫法 typedef unsigned int UINT; template <class T> class Stack { public:Stack(void); // 初始化棧~Stack(void); // 析構棧bool Empty() const; // 判斷是否為空void Clear(); // 則清空棧StackNode<T> GetTop() const; // 得到棧頂元素UINT GetLength() const; // 返回棧的長度void Push(T &data); //往棧中壓入數據void Pop(); //將棧頂數據彈出void print(); //自己加的接口,打印輸出stack內容 private:StackNode<T> m_pTop; // 棧頂元素UINT m_nStackLen; // 棧長度 };#endif //_STACK_H2.2 類實現文件 stack.cpp
// // Created by mingm on 2019/3/26. // #include "stack.h" #include <iostream> using namespace std; template <class T> Stack<T>::Stack():m_pTop(NULL),m_nStackLen(0){} template <class T> Stack<T>::~Stack() { Clear(); } template <class T> bool Stack<T>::Empty() const {return m_nStackLen == 0; } template <class T> void Stack<T>::Clear() {while(m_pTop != NULL){Pop();} } template <class T> void Stack<T>::Push(T &data) {StackNode<T> newNode = new SNode<T>;newNode->data = data;newNode->pNext = NULL;if(m_pTop == NULL){m_pTop = newNode;}else{newNode->pNext = m_pTop;m_pTop = newNode;}m_nStackLen++; } template <class T> void Stack<T>::Pop() {if(m_pTop != NULL){StackNode<T> temp = m_pTop->pNext;delete m_pTop;m_pTop = temp;m_nStackLen--;} } template <class T> StackNode<T> Stack<T>::GetTop() const {return m_pTop; } template <class T> UINT Stack<T>::GetLength() const {return m_nStackLen; } template <class T> void Stack<T>::print() {cout << "----stack top----" << endl;StackNode<T> temp = m_pTop;size_t i = 0;while(temp != NULL){cout << "No." << ++i << " elem " << temp->data << endl;temp = temp->pNext;}cout << "----stack bottom----" << endl; }2.3 鏈式棧 測試主程序
#include "stack.cpp" #include <string> #include <iostream>using namespace std; int main() {for(int i = 0; i < 10; ++i){int nums = 0;Stack<int> intstack;if(intstack.Empty())cout << "intstack is empty!" << endl;cout << "after push nums: " << endl;while(nums < i){intstack.Push(nums);nums++;}intstack.print();intstack.Pop();cout << "len of stack is " << intstack.GetLength() << endl;if(intstack.GetTop())cout << "top elem is " << intstack.GetTop()->data << endl;if(!intstack.Empty())cout << "intstack is not empty!" << endl;intstack.print();cout << "---------------------------------" << endl;}cout << "以下測試一個字符串是否有非法格式的括號" << endl;char conti = 'y', str;while(conti == 'y'|| conti == 'Y'){bool legal = true;Stack<char> charstack;cout << "please enter a string to check its brackets legal or not !" << endl;while(cin.get(str) && str != '\n') //不斷地獲取輸入的字符{if(str == '{' || str == '[' || str == '(') //遇到左括號不斷地壓棧{charstack.Push(str);continue;}switch(str) //遇到非左括號{case '}':if(charstack.GetTop() && charstack.GetTop()->data == '{') //棧不為空且棧頂與右括號匹配charstack.Pop(); //刪除左括號elselegal = false; //直接遇上右括號,非法;or 棧頂與當前右括號不匹配break;case ']':if(charstack.GetTop() && charstack.GetTop()->data == '[')charstack.Pop();elselegal = false;break;case ')':if(charstack.GetTop() && charstack.GetTop()->data == '(')charstack.Pop();elselegal = false;break;default:break;}if(!legal)break; //如果非法,不必循環了,直接退出}if(legal && charstack.Empty()) //如果合法,且符號都匹配了(棧為空)cout << "legal string !" << endl;else{cout << "illegal string !" << endl;cin.ignore(10000,'\n'); //清除非法字符后面尚未get的字符}cout << "continue? y/n: " ;cin >> conti;cin.get();}return 0; }3.valgrind測試正確
總結
以上是生活随笔為你收集整理的数据结构--栈--顺序栈/链式栈(附: 字符括号合法配对检测)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 利用python提取网站曲线图数据
- 下一篇: LeetCode 476. 数字的补数(