#include #include #include #include #include struct stack{ char data[100]; int size; }stack; ///add bracket to stack and increment size void push(char ch){ if(stack.size < 100){ stack.size++; stack.data[stack.size] = ch; } else exit(0); } ///if i have opening bracket in stack, then decrement size void pop(){ if(stack.size >= 0) stack.size--; else exit(0); } ///compare brackets bool find_pair(char a, char b){ if(a == '(' && b == ')') return true; if(a == '{' && b == '}') return true; if(a == '<' && b == '>') return true; if(a == '[' && b == ']') return true; return false; } ///function to find right pair char right_pair(char a){ char b; if(a == '(') b = ')'; if(a == '{') b = '}'; if(a == '[') b = ']'; if(a == '<') b = '>'; return b; } ///find the last opening bracket in the stack char gettop(){ return stack.data[stack.size]; } int main(){ char line[100]; stack.size = -1; printf("Read: "); char *x = fgets(line, 100, stdin); printf("%s", line); int l = strlen(line); int i, j = -1, f = -1;; char *o_bracket = calloc(l, sizeof(char)); char *c_bracket = calloc(l, sizeof(char)); for(i = 0; i < l; i++){ if(line[i] == '{' || line[i] == '(' || line[i] == '[' || line[i] == '<'){ push(line[i]); j++; f++; o_bracket[j] = gettop(); //get opening bracket from the stack c_bracket[f] = right_pair(o_bracket[j]); //get closing bracket } if(line[i] == '}' || line[i] == ')' || line[i] == ']' || line[i] == '>'){ if(stack.size == -1){ //if there is no opening bracket in the stack printf("Unexpected closing bracket %c in %d\n", line[i], i); return 0; } else if(!find_pair(gettop(), line[i])){ //if there is another closing bracket printf("Crossed bracket %c in %d, expected %c \n", line[i], i, c_bracket[f]); return 0; } else{ c_bracket[f] = 0; //if closing bracket is correct then reducee array f--; //if i didn't find a correct bracket, then keep it in the array c_bracket pop(); } } } int begin = 0; int end = strlen(c_bracket); int temp; //now i have all missing closing brackets in array //flip array while(begin < end){ temp = c_bracket[begin]; c_bracket[begin++] = c_bracket[--end]; c_bracket[end] = temp; } //if program pop all opening brackets from the stack, then stack size must be -1; if(stack.size == -1){ printf("All brackets OK\n"); } //if no, then program didn't find closing bracket else { printf("Missing closing brackets: %s\n", c_bracket); } free(o_bracket); free(c_bracket); return 0; }