棧C/C++實現(資料結構嚴蔚敏版)
阿新 • • 發佈:2019-01-10
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 0 typedef 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); }