usaa20/a2/program.c
Maryna Kravtsova c88cf9bbbb a2
2020-10-21 11:29:36 +02:00

112 lines
2.0 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){
assert(s.size < 100);
s.size++;
s.data[s.size] = ch;
}
else{
exit(0);
}
}
void pop(){
if(s.size > 0){
assert(s.size > 0);
s.size--;
}
else {
exit(0);
}
}
bool find_pair(char a, char b){
if(a == '(' && b == ')')
return true;
else if(a == '{' && b == '}')
return true;
else if(a == '<' && b == '>')
return true;
else if(a == '[' && b == ']')
return true;
return false;
}
char right_pair(char a){
char b;
if(a == '('){
b = ')';
}
else if(a == '{'){
b = '}';
}
else if(a == '['){
b = ']';
}
else 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);
int l = strlen(line);
int i, j;
for(i = 0; i < l; i++){
if(line[i] == '{' || line[i] == '(' || line[i] == '[' || line[i] == '<'){
push(line[i]);
}
else if(line[i] == '}' || line[i] == ')' || line[i] == ']' || line[i] == '>'){
char a = gettop();
if(a != '(' || a != '{' || a != '<' || a != '['){
printf("Unexpected closing brocket %c in %d\n", line[i], i);
return 0;
}
else if(s.size == -1 && !find_pair(gettop(), line[i])){
char b = right_pair(a);
printf("Crossed bracket %c in %d, expected %c\n", line[i], i, b);
return 0;
}
else{
pop();
}
}
}
if(s.size == -1){
printf("All brackest are OK\n");
}
return 0;
}