之前學習了棧的基本操作,並且學習了棧的兩種實現方式:鏈式存儲和順序存儲(數組)。現在看看棧都有哪些應用。棧的一個主要應用是平衡符號。
初學者在編寫代碼並且編譯時,難免會因爲少寫了一個')'和被編譯器報錯。也就是說,編譯器會去匹配括號是否匹配。當你輸入了一個'(',很自然編譯器回去檢查你是否有另一個')'符號與之匹配。如果所有的括號都能夠成對出現,那麼編譯器是能夠通過的。否則編譯器會報錯。例如字符序列“(a+b)”是匹配的,而字符序列"(a+b]"則不是。
在檢測括號匹配的算法中使用到了棧,算法描述如下:創建一個空棧,讀取字符序列直到結尾。如果字符是開放符號'(''[''{',將其入棧;如果是一個封閉符號')'']''}',則當棧爲空時報錯。否則,將棧頂元素彈出。如果彈出的符號不是對應的開放符號,則報錯。當字符序列結束,判斷棧是否爲空,爲空則報錯。
下面是我的實現代碼:
- #include <stdio.h>
- #include <stdlib.h>
- #define ElementType char
- typedef struct Node *PtrToNode;
- typedef PtrToNode Stack;
- typedef struct Node
- {
- ElementType Element;
- PtrToNode Next;
- };
- int IsEmpty(Stack S);
- Stack CreateStack();
- void DisposeStack(Stack S);
- void MakeEmpty(Stack S);
- void Push(ElementType X,Stack S);
- ElementType Top(Stack S);
- void Pop(Stack S);
- //判斷棧是否爲空
- int IsEmpty(Stack S)
- {
- return S->Next == NULL;
- }
- //創建鏈棧
- Stack CreateStack()
- {
- Stack S = malloc(sizeof(struct Node));
- if(S == NULL)
- {
- printf("No enough memory!");
- return NULL;
- }
- S->Next = NULL;
- MakeEmpty(S);
- return S;
- }
- void MakeEmpty(Stack S)
- {
- if(S == NULL)
- {
- printf("Use CreateStack First!");
- }
- else
- {
- while(!IsEmpty(S))
- {
- Pop(S);
- }
- }
- }
- void Push(ElementType X,Stack S)
- {
- PtrToNode Tmp;
- Tmp = malloc(sizeof(struct Node));
- if(Tmp != NULL)
- {
- Tmp->Element = X;
- Tmp->Next = S->Next;
- S->Next = Tmp;
- }
- else
- {
- printf("Out of space!");
- }
- }
- void Pop(Stack S)
- {
- if(IsEmpty(S))
- {
- printf("The Stack is Empty!");
- }
- else
- {
- PtrToNode Tmp = S->Next;
- S->Next = Tmp->Next;
- free(Tmp);
- }
- }
- ElementType Top(Stack S)
- {
- if(IsEmpty(S))
- {
- printf("The stack is empty!");
- return 0;
- }
- else
- {
- return S->Next->Element;
- }
- }
- //平衡符號判斷
- void balance(char *ch,Stack S)
- {
- ElementType c;
- MakeEmpty(S);
- while((c=*ch) != '\0')
- {
- printf("%c\n",c);
- switch(c)
- {
- case '(':
- case '[':
- case '{':
- Push(c,S);
- break;
- case ')':
- if(IsEmpty(S))
- {
- fprintf(stderr,"The symbols not balance!\n");
- return;
- }
- else
- {
- if(Top(S)=='(')
- {
- Pop(S);
- }
- else
- {
- fprintf(stderr,"The symbols not balance!\n");
- return;
- }
- }
- break;
- case ']':
- if(IsEmpty(S))
- {
- fprintf(stderr,"The symbols not balance!\n");
- return;
- }
- else
- {
- if(Top(S)=='[')
- {
- Pop(S);
- }
- else
- {
- fprintf(stderr,"The symbols not balance!\n");
- return;
- }
- }
- break;
- case '}':
- if(IsEmpty(S))
- {
- fprintf(stderr,"The symbols not balance!\n");
- return;
- }
- else
- {
- if(Top(S)=='{')
- {
- Pop(S);
- }
- else
- {
- fprintf(stderr,"The symbols not balance!\n");
- return;
- }
- }
- break;
- default:
- break;
- }
- ch++;
- }
- if(IsEmpty(S))
- {
- fprintf(stdout,"The Symbols Balance!\n");
- }
- else
- {
- fprintf(stderr,"The Symbols Not Balance!\n");
- }
- }
- int main(void)
- {
- char ch[] = "(a+b){[d]c*d}{";
- Stack S = CreateStack();
- balance(ch,S);
- return 0;
- }