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