usaa24/a1/program.c

66 lines
1.8 KiB
C
Raw Normal View History

2024-10-26 18:43:36 +00:00
#include <stdio.h>
2024-10-26 19:31:08 +00:00
#include <string.h>
2024-10-26 18:43:36 +00:00
#define MAX 100
2024-10-26 19:31:08 +00:00
// Pomocná funkcia na kontrolu páru zátvoriek
int is_matching_pair(char open, char close) {
return (open == '(' && close == ')') ||
(open == '{' && close == '}') ||
(open == '[' && close == ']') ||
(open == '<' && close == '>');
}
// Funkcia na kontrolu správnosti zátvoriek
void check_brackets(const char *code) {
char stack[MAX];
int stack_top = -1; // vrchol zásobníka
printf("Read: %s\n", code);
2024-10-26 19:20:18 +00:00
2024-10-26 19:31:08 +00:00
for (int i = 0; code[i] != '\0'; i++) {
char c = code[i];
// Ak je znak otváracia zátvorka, pridaj ho na zásobník
if (c == '(' || c == '{' || c == '[' || c == '<') {
if (stack_top >= MAX - 1) {
printf("Stack overflow at position %d\n", i);
return;
2024-10-26 19:20:18 +00:00
}
2024-10-26 19:31:08 +00:00
stack[++stack_top] = c;
2024-10-26 19:20:18 +00:00
}
2024-10-26 19:31:08 +00:00
// Ak je znak zatváracia zátvorka
else if (c == ')' || c == '}' || c == ']' || c == '>') {
if (stack_top < 0) {
printf("Unexpected closing bracket %c at position %d\n", c, i);
return;
}
char top = stack[stack_top--];
if (!is_matching_pair(top, c)) {
printf("Crossed bracket %c in %d, expected %c\n", c, i, top);
return;
}
2024-10-26 19:20:18 +00:00
}
}
2024-10-26 19:26:38 +00:00
2024-10-26 19:31:08 +00:00
// Skontroluj, či sú všetky zátvorky uzavreté
if (stack_top >= 0) {
printf("Unmatched bracket at the end\n");
} else {
printf("All brackets OK\n");
}
2024-10-26 18:43:36 +00:00
}
int main() {
2024-10-26 19:31:08 +00:00
char code[MAX];
fgets(code, MAX, stdin);
// Odstráň novoriadok na konci
code[strcspn(code, "\n")] = '\0';
// Skontroluj zátvorky
check_brackets(code);
2024-10-26 18:43:36 +00:00
return 0;
2024-10-26 19:31:08 +00:00
}