usaa20/a2/program.c

120 lines
2.4 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <ctype.h>
struct stack{
char data[100];
int size;
}stack;
void push(char ch){
if(stack.size < 100){
stack.size++;
stack.data[stack.size] = ch;
}
else
exit(0);
}
void pop(){
if(stack.size >= 0)
stack.size--;
else
exit(0);
}
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;
}
char right_pair(char a){
char b;
if(a == '(')
b = ')';
if(a == '{')
b = '}';
if(a == '[')
b = ']';
if(a == '<')
b = '>';
return b;
}
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 *l_bracket = calloc(l, sizeof(char));
char *r_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++;
l_bracket[j] = gettop();
r_bracket[f] = right_pair(l_bracket[j]);
}
if(line[i] == '}' || line[i] == ')' || line[i] == ']' || line[i] == '>'){
if(stack.size == -1){
printf("Unexpected closing bracket %c in %d\n", line[i], i);
return 0;
}
else if(!find_pair(gettop(), line[i])){
printf("Crossed bracket %c in %d, expected %c \n", line[i], i, r_bracket[j]);
return 0;
}
else{
r_bracket[f] = 0;
f--;
pop();
}
}
}
int begin = 0;
int end = strlen(r_bracket);
int temp;
//printf("%s", b);
while(begin < end){
temp = r_bracket[begin];
r_bracket[begin++] = r_bracket[--end];
r_bracket[end] = temp;
}
if(stack.size == -1){
printf("All brackets OK\n");
}
else {
printf("Missing closing brackets: %s\n", r_bracket);
}
free(l_bracket);
free(r_bracket);
return 0;
}