Initializacia
This commit is contained in:
parent
e9423093a5
commit
138c5f4e91
71
a1/program.c
71
a1/program.c
@ -1 +1,72 @@
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#define MAX_LEN 101
|
||||
|
||||
typedef struct {
|
||||
char bracket;
|
||||
int position;
|
||||
} StackItem;
|
||||
|
||||
int is_opening(char ch) {
|
||||
return ch == '(' || ch == '{' || ch == '[' || ch == '<';
|
||||
}
|
||||
|
||||
int is_closing(char ch) {
|
||||
return ch == ')' || ch == '}' || ch == ']' || ch == '>';
|
||||
}
|
||||
|
||||
char matching_bracket(char ch) {
|
||||
switch (ch) {
|
||||
case ')': return '(';
|
||||
case '}': return '{';
|
||||
case ']': return '[';
|
||||
case '>': return '<';
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
|
||||
void check_brackets(const char *line) {
|
||||
StackItem stack[MAX_LEN];
|
||||
int stack_top = -1;
|
||||
|
||||
printf("Read: %s\n", line);
|
||||
|
||||
for (int i = 0; line[i] != '\0'; i++) {
|
||||
char ch = line[i];
|
||||
|
||||
if (is_opening(ch)) {
|
||||
if (stack_top < MAX_LEN - 1) {
|
||||
stack[++stack_top].bracket = ch;
|
||||
stack[stack_top].position = i;
|
||||
} else {
|
||||
printf("Error: Stack overflow\n");
|
||||
return;
|
||||
}
|
||||
} else if (is_closing(ch)) {
|
||||
if (stack_top >= 0 && stack[stack_top].bracket == matching_bracket(ch)) {
|
||||
stack_top--;
|
||||
} else {
|
||||
printf("Crossed bracket %c in %d, expected %c\n", ch, i,
|
||||
stack_top >= 0 ? matching_bracket(stack[stack_top].bracket) : '#');
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (stack_top >= 0) {
|
||||
printf("Unmatched bracket %c in %d\n", stack[stack_top].bracket, stack[stack_top].position);
|
||||
} else {
|
||||
printf("All brackets OK\n");
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
char line[MAX_LEN];
|
||||
if (fgets(line, sizeof(line), stdin)) {
|
||||
line[strcspn(line, "\n")] = '\0';
|
||||
check_brackets(line);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user