usaa20/a2/program.c
Maryna Kravtsova a2310e4d2d akt
2020-10-21 14:46:30 +02:00

116 lines
2.2 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <stdbool.h>
#include <ctype.h>
struct stack{
char data[100];
int size;
}s;
void push(char ch){
if(s.size < 100){
s.size++;
s.data[s.size] = ch;
}
else
exit(0);
}
void pop(){
if(s.size >= 0)
s.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 s.data[s.size];
}
int main(){
char line[100];
s.size = -1;
printf("Read: ");
char *x = fgets(line, 100, stdin);
printf("%s", line);
int l = strlen(line);
int i, j = 0;
char *a = calloc(l, sizeof(char));
char *b = calloc(l, sizeof(char));
for(i = 0; i < l; i++){
if(line[i] == '{' || line[i] == '(' || line[i] == '[' || line[i] == '<'){
push(line[i]);
a[j] = gettop();
b[j] = right_pair(a[j]);
j++;
}
if(line[i] == '}' || line[i] == ')' || line[i] == ']' || line[i] == '>'){
if(s.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, b);
return 0;
}
else{
pop();
}
}
}
int begin = 0;
int end = strlen(b);
int h;
while(begin < end){
h = b[begin];
b[begin] = b[--end];
b[end] = h;
}
if(s.size == -1){
printf("All brackets OK\n");
}
else {
printf("Missing closing brackets: %s \n", b);
}
free(a);
free(b);
return 0;
}