Update 'a2/program.c'

This commit is contained in:
Maryna Kravtsova 2020-10-24 16:50:10 +00:00
parent adc2849984
commit ffb35f129d

View File

@ -9,6 +9,8 @@ struct stack{
int size;
}stack;
///add bracket to stack
void push(char ch){
if(stack.size < 100){
stack.size++;
@ -16,7 +18,9 @@ void push(char ch){
}
else
exit(0);
}
}
///if i have opening bracket in stack, then decrement size
void pop(){
if(stack.size >= 0)
@ -25,6 +29,8 @@ void pop(){
exit(0);
}
///compare brackets
bool find_pair(char a, char b){
if(a == '(' && b == ')')
return true;
@ -36,8 +42,10 @@ bool find_pair(char a, char b){
return true;
return false;
}
///function to find right pair
char right_pair(char a){
char b;
if(a == '(')
@ -52,6 +60,8 @@ char right_pair(char a){
return b;
}
///find the last opening bracket in the stack
char gettop(){
return stack.data[stack.size];
}
@ -68,53 +78,60 @@ int main(){
int l = strlen(line);
int i, j = -1, f = -1;;
char *l_bracket = calloc(l, sizeof(char));
char *r_bracket = calloc(l, sizeof(char));
char *o_bracket = calloc(l, sizeof(char));
char *c_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]);
o_bracket[j] = gettop(); //get opening bracket from the stack
c_bracket[f] = right_pair(o_bracket[j]); //get closing bracket
}
if(line[i] == '}' || line[i] == ')' || line[i] == ']' || line[i] == '>'){
if(stack.size == -1){
if(line[i] == '}' || line[i] == ')' || line[i] == ']' || line[i] == '>'){
if(stack.size == -1){ //if there is no opening bracket in the stack
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[f]);
else if(!find_pair(gettop(), line[i])){ //if there is another closing bracket
printf("Crossed bracket %c in %d, expected %c \n", line[i], i, c_bracket[f]);
return 0;
}
else{
r_bracket[f] = 0;
f--;
c_bracket[f] = 0; //if closing bracket is correct then reducee array
f--; //if i didn't find a correct bracket, then keep it in the array
pop();
}
}
}
int begin = 0;
int end = strlen(r_bracket);
int end = strlen(c_bracket);
int temp;
//now i have all missing closing brackets in array
//flip array
while(begin < end){
temp = r_bracket[begin];
r_bracket[begin++] = r_bracket[--end];
r_bracket[end] = temp;
temp = c_bracket[begin];
c_bracket[begin++] = c_bracket[--end];
c_bracket[end] = temp;
}
//if program pop all opening brackets from the stack, then stack size must be -1;
if(stack.size == -1){
printf("All brackets OK\n");
}
//if no, then program didn't find closing bracket
else {
printf("Missing closing brackets: %s\n", r_bracket);
printf("Missing closing brackets: %s\n", c_bracket);
}
free(l_bracket);
free(r_bracket);
free(o_bracket);
free(c_bracket);
return 0;
}