This commit is contained in:
Deinerovych 2024-10-29 15:09:54 +01:00
parent a8d85d812d
commit 23cf99cf01

View File

@ -10,9 +10,14 @@ int is_matching_pair(char open, char close) {
(open == '<' && close == '>'); (open == '<' && close == '>');
} }
char matching_close(char open) {
return open == '(' ? ')' :
open == '{' ? '}' :
open == '[' ? ']' : '>';
}
void check_brackets(const char *code) { void check_brackets(const char *code) {
char stack[MAX_LEN]; char stack[MAX_LEN];
int positions[MAX_LEN];
int top = -1; int top = -1;
printf("Read: %s\n", code); printf("Read: %s\n", code);
@ -23,7 +28,6 @@ void check_brackets(const char *code) {
if (ch == '(' || ch == '{' || ch == '[' || ch == '<') { if (ch == '(' || ch == '{' || ch == '[' || ch == '<') {
if (top < MAX_LEN - 1) { if (top < MAX_LEN - 1) {
stack[++top] = ch; stack[++top] = ch;
positions[top] = i;
} else { } else {
printf("Stack overflow at position %d\n", i); printf("Stack overflow at position %d\n", i);
return; return;
@ -35,10 +39,7 @@ void check_brackets(const char *code) {
return; return;
} }
if (!is_matching_pair(stack[top], ch)) { if (!is_matching_pair(stack[top], ch)) {
printf("Crossed bracket %c in %d, expected %c\n", ch, i, printf("Crossed bracket %c in %d, expected %c\n", ch, i, matching_close(stack[top]));
stack[top] == '(' ? ')' :
stack[top] == '{' ? '}' :
stack[top] == '[' ? ']' : '>');
return; return;
} }
top--; top--;
@ -46,10 +47,11 @@ void check_brackets(const char *code) {
} }
if (top != -1) { if (top != -1) {
printf("Missing closing brackets: %c\n", printf("Missing closing brackets: ");
stack[top] == '(' ? ')' : while (top != -1) {
stack[top] == '{' ? '}' : printf("%c", matching_close(stack[top--]));
stack[top] == '[' ? ']' : '>'); }
printf("\n");
} else { } else {
printf("All brackets OK\n"); printf("All brackets OK\n");
} }