final vers

This commit is contained in:
Maryna Kravtsova 2020-10-21 16:14:51 +02:00
parent 01620f4b61
commit aa8545df6b

View File

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