This commit is contained in:
Maryna Kravtsova 2020-10-21 14:21:10 +02:00
parent c88cf9bbbb
commit bef9c5185a

View File

@ -12,34 +12,30 @@ struct stack{
void push(char ch){ void push(char ch){
if(s.size < 100){ if(s.size < 100){
assert(s.size < 100);
s.size++; s.size++;
s.data[s.size] = ch; s.data[s.size] = ch;
} }
else{ else
exit(0); exit(0);
}
} }
void pop(){ char pop(){
if(s.size > 0){ if(s.size > 0){
assert(s.size > 0);
s.size--; s.size--;
return (s.data[s.size]);
} }
else { else
exit(0); exit(0);
}
} }
bool find_pair(char a, char b){ bool find_pair(char a, char b){
if(a == '(' && b == ')') if(a == '(' && b == ')')
return true; return true;
else if(a == '{' && b == '}') if(a == '{' && b == '}')
return true; return true;
else if(a == '<' && b == '>') if(a == '<' && b == '>')
return true; return true;
else if(a == '[' && b == ']') if(a == '[' && b == ']')
return true; return true;
return false; return false;
@ -47,18 +43,15 @@ bool find_pair(char a, char b){
} }
char right_pair(char a){ char right_pair(char a){
char b; char b;
if(a == '('){ if(a == '(')
b = ')'; b = ')';
} if(a == '{')
else if(a == '{'){
b = '}'; b = '}';
} if(a == '[')
else if(a == '['){
b = ']'; b = ']';
} if(a == '<')
else if(a == '<'){
b = '>'; b = '>';
}
return b; return b;
} }
@ -74,38 +67,50 @@ int main(){
printf("Read: "); printf("Read: ");
char *x = fgets(line, 100, stdin); char *x = fgets(line, 100, stdin);
printf("%s", line);
int l = strlen(line); int l = strlen(line);
int i, j; int i, j = 0;
char *a = calloc(l, sizeof(char));
char *b = calloc(l, sizeof(char));
for(i = 0; i < l; i++){ for(i = 0; i < l; i++){
//a[i] = gettop();
// b[i] = right_pair(a[i]);
if(line[i] == '{' || line[i] == '(' || line[i] == '[' || line[i] == '<'){ if(line[i] == '{' || line[i] == '(' || line[i] == '[' || line[i] == '<'){
push(line[i]); push(line[i]);
a[j] = gettop();
b[j] = right_pair(a[j]);
j++;
//printf("%c", b[i]);
} }
else if(line[i] == '}' || line[i] == ')' || line[i] == ']' || line[i] == '>'){ if(line[i] == '}' || line[i] == ')' || line[i] == ']' || line[i] == '>'){
//a[i] = gettop();
char a = gettop(); //b[i] = right_pair(a[i]);
if(a != '(' || a != '{' || a != '<' || a != '['){ if(s.size == -1){
printf("Unexpected closing brocket %c in %d\n", line[i], i); printf("Unexpected closing bracket %c in %d\n", line[i], i);
return 0; return 0;
} }
else if(s.size == -1 && !find_pair(gettop(), line[i])){ else if(!find_pair(gettop(), line[i])){
char b = right_pair(a);
printf("Crossed bracket %c in %d, expected %c\n", line[i], i, b); printf("Crossed bracket %c in %d, expected %c\n", line[i], i, b);
return 0; return 0;
} }
else{ else{
pop(); pop();
} }
} }
} }
i = 0;
if(s.size == -1){ if(s.size == -1){
printf("All brackest are OK\n"); printf("All brackets OK\n");
} }
else {
printf("Missing closing brackets: %s \n", b);
}
free(a);
free(b);
return 0; return 0;
} }