順序棧
#include<stdio.h>//初始化棧[順序棧]void initStack(SeqStack * s){s->top=-1;}//進棧int push(SeqStack *s,StackElementType x){if(s->top == Stack_size-1){return false;}s->top++;s->elem[s->top]=x;return true;}//出棧int Pop(SeqStack *s,StackElementType *x){if(s->top==-1){return false;}else{*x=s->elem[s->top];s->top--;return true;}}//取棧頂元素int GetTop(SeqStack *s,StackElementType *x){if(s->top==-1){return false;}else{*x=s->elem[s->s->top];return true;}}int main(void){return 0;}
鏈棧
#include<stdio.h>typedef struct node{StackElementType data;struct node *next;}LinkStackNode;typedef LinkStackNode * LinkStack;//進棧【鏈棧】int push(SeqStack top,StackElementType x){LinkStackNode * temp;temp = (LinkStackNode)malloc(sizeof(LinkStackNode));if(temp==NULL)//申請空間失敗return false;temp->data=x;temp->next=top->next;top->next=temp;return true;}//出棧【鏈棧】int Pop(SeqStack top,StackElementType *x){LinkStackNode * temp;temp=top->next;if(temp==NULL)//棧為空白return false;top->next=temp->next;*x=temp->data;free(temp);return true;}int main(void){return 0;}
括弧匹配演算法
#include<stdio.h>//括弧匹配演算法void BracketMatch(char *str)//參數為輸入的字串{Stack s,int i,char ch;InitStack(&s);for(i=0;str[i]!='\0';i++){switch(str[i]){case '(':case '[':case '{':Push(&s,str[i]);break;case ')':case ']':case '}':if(IsEmpty(&s)){printf("右括弧多餘");return;}else{GetTop(&s,&ch);if(Match(ch,str[i]))Pop(&s,&ch);elseprintf("對應的括弧不同類");}}}if(IsEmpty(&s))printf("括弧匹配");elseprintf("括弧不匹配");}int main(void){return 0;}