/* Create a stack to implement matching of parentheses. Create a stack and determine whether the stack is empty */# include <stdio. h> # include <stdlib. h> # include <string. h ># define status inttypedef struct node {char ch; node * Next;} snode; typedef struct {snode * Top; // snode * base;} stack; // create an empty stack base with a value of null. Top points to the top element of the stack. Status initstack (stack & S) {S. top = NULL; return 0;} bool empty (stack s) {If (null = S. top) return 1; return 0;} status pushstack (stack & S, char e) // inbound stack {snode * P; P = (snode *) malloc (Si Zeof (snode); If (null = P) {printf ("memory allocation failed, terminate the program! \ N "); exit (-1);} p-> CH = E; P-> next = S. top; S. top = P; // printf ("% C stack succeeded \ n", e); Return 0;} status popstack (stack & S, char & E) // output stack {snode * q; If (null! = S. top) {// printf ("% x & \ n", S. top); E = S. top-> CH; q = S. top; S. top = Q-> next; free (Q); // printf ("% C success output stack \ n", e); return 1 ;} else {printf ("the stack is empty. An error occurred while releasing the stack! \ N "); Return 0 ;}} status clearstack (stack & S) // clear stack {While (null! = S. top) {snode * q; q = S. top; free (Q); S. top = S. top-> next ;}} status matching (stack & S, char STR [], int Len) {int I; char E; for (I = 0; I <Len; ++ I) {If (STR [I] = '{' | STR [I] = '[' | STR [I] = '(') pushstack (S, STR [I]); else if (empty (s) {printf ("Mismatched \ n"); Return 0 ;} else {If (STR [I] = '}') {If (S. top-> CH = '{') popstack (S, e); else {printf ("unmatched \ n"); Return 0 ;}} else if (STR [I] = ']') {If (S. top-> CH = '[') popstack (S, e); else {prin TF ("unmatched \ n"); // printf ("unmatched, arriving at an unexpected customer \ n"); Return 0 ;}} else if (STR [I] = ') {If (S. top-> CH = '(') popstack (S, e); else {printf ("unmatched \ n"); Return 0 ;}}}} if (empty (s) printf ("matched \ n"); else {printf ("unmatched \ n") ;}} status main () {stack S; initstack (s); int I, Len; char STR [20], ch; while (~ Scanf ("% s", STR) {Len = strlen (STR); matching (S, STR, Len); clearstack (s) ;}return 0 ;}
Matching brackets (implementation of chain stack)