栈C/C++实现(数据结构严蔚敏版)
生活随笔
收集整理的這篇文章主要介紹了
栈C/C++实现(数据结构严蔚敏版)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、頭文件:stack.h
#include<iostream> #include<malloc.h> using namespace std; typedef int Status; typedef char ElemType;#define ok 1 #define error 0 #define Stack_Init_Size 10 #define Stack_ADD 10 #define flow 0typedef struct{ElemType* base;ElemType* top;int stacksize;}SqStack;//初始化,構造一個空棧 Status InitStack(SqStack& S);//如果棧不為空,就獲取棧頂數據 Status GetTop(const SqStack& S, ElemType& e);//壓棧 Status Push(SqStack& S, ElemType& e);//如果棧頂不為空,彈出棧頂數據 Status Pop(SqStack& S, ElemType& e);//置為空棧 Status StackEmpty(SqStack& S);//打印棧中的數據 Status Print(const SqStack& S);2、源文件stack.cpp:
#include "stack.h"//初始化,構造一個空棧 Status InitStack(SqStack& S){S.base = NULL;S.top = NULL; S.base = (ElemType *)malloc(Stack_Init_Size * sizeof(ElemType));if(!S.base) exit(flow);S.top = S.base;S.stacksize = Stack_Init_Size;return ok; }//如果棧不為空,就獲取棧頂數據 Status GetTop(const SqStack& S, ElemType& e){if (S.top == S.base) return error;e = *(S.top-1);return ok; }//壓棧 Status Push(SqStack& S, ElemType& e){//計算棧頂和棧底的距離 int length = S.top - S.base;if(S.stacksize == length){ S.base = (ElemType*)realloc(S.base, (Stack_ADD + S.stacksize) * sizeof(ElemType)); S.top = S.base + S.stacksize; S.stacksize = S.stacksize + Stack_ADD;if(!S.base) exit(flow); }*S.top = e;S.top++;return ok; }//如果棧頂不為空,彈出棧頂數據 Status Pop( SqStack& S, ElemType& e){if (S.top == S.base) return error;e = *(S.top-1);S.top--;return ok; }//將站置空 Status StackEmpty(SqStack& S) {if (S.top == S.base){return ok;}else{free(S.base);S.top = S.base = NULL;return error;} } //打印棧中數據 Status Print(const SqStack& S){if(S.base == S.top){cout<<"這是一個空棧,沒有數據"<<endl;return error;}else{ElemType* p;p = S.base; cout<<"棧中的數據如下:"<<endl; while(p != S.top){cout<<*p<<" ";p++;}cout<<endl;return ok;} }3、測試文件test.cpp:
#include "stack.h" #include<time.h> #include<stdio.h> #include<string>int main(void){SqStack S;ElemType e, e1;int n;InitStack(S);cout<<"請輸入你要輸入括號個數,必須是偶數"<<endl;cin>>n;cout<<"請輸入"<<n<<"個括號"<<endl;for(int i=0; i<n; i++){cin>>e;if(S.top - S.base >= 1){GetTop(S, e1);if(e1+2 == e)Pop(S, e1);}else{Push(S, e);}}if(S.base == S.top){cout<<"括號匹配是對的"<<endl; }else{cout<<"括號不匹配"<<endl;}free(S.base);}總結
以上是生活随笔為你收集整理的栈C/C++实现(数据结构严蔚敏版)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 循环链表C/C++实现(数据结构严蔚敏版
- 下一篇: 队列顺序结构C/C++实现(数据结构严蔚