728x90
๐ต ๊ดํธ ๊ฒ์ฌ ์กฐ๊ฑด
- ์ค๋ฅธ์ชฝ ๊ดํธ ๋ง๋ ๋๊น์ง ์ผ์ชฝ ๊ดํธ push
- ์ค๋ฅธ์ชฝ ๊ดํธ ๋ง๋ฌ์ ๊ฒฝ์ฐ
- ์คํ์ ๋ค์ด์๋ ์ผ์ชฝ ๊ดํธ pop
- ๐ฅ์ค๋ฅ์ธ ๊ฒฝ์ฐ
- ์คํ์ด ๋น์ด์์ ๋
- ๊ดํธ ์ข ๋ฅ๊ฐ ๋ง์ง ์์ ๋
- ์ค๋ฅธ์ชฝ ๊ดํธ ๋๊น์ง ์ค์บํ์ ๊ฒฝ์ฐ
- ๐ฅ์ค๋ฅ์ธ ๊ฒฝ์ฐ
- ์คํ์ด ๋น์ด์์ง ์์์ ๋
- ๐ฅ์ค๋ฅ์ธ ๊ฒฝ์ฐ
๐ก ๊ดํธ ๊ฒ์ฌ ์ฝ๋
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100
typedef char element;
typedef struct {
int top;
element data[MAX_SIZE];
} StackType;
void init(StackType* s) {
s->top = -1;
}
int is_full(StackType* s) {
return s->top == MAX_SIZE - 1;
}
int is_empty(StackType* s) {
return s->top == -1;
}
void push(StackType* s, element ch) {
if (is_full(s)) {
printf("์คํ์ด ๊ฐ๋์ฐผ์ต๋๋ค.\n");
return;
}
else {
s->data[++(s->top)] = ch;
}
}
char pop(StackType* s) {
if (is_empty(s)) {
printf("์คํ ๊ณต๋ฐฑ ์๋ฌ\n");
return;
}
else {
return s->data[(s->top)--];
}
}
int check_matching(element* exp) {
StackType s;
init(&s);
char ch, pop_ch;
int i, n = strlen(exp);
for (i = 0; i < n; i++) {
ch = exp[i];
switch (ch) {
case '(': case '[': case '{': // ์ผ์ชฝ ๊ดํธ์ผ ๊ฒฝ์ฐ ์คํ์ push
push(&s, ch);
break;
case ')': case ']': case '}': // ์ค๋ฅธ์ชฝ ๊ดํธ๋ฅผ ๋ง๋ฌ์ ๋
if (is_empty(&s)) return 0; // ์คํ์ด ๋น์ด์์ ๊ฒฝ์ฐ ์ค๋ฅ
else { // ๊ดํธ ์ข
๋ฅ๊ฐ ๋ง์ง ์๋ ๊ฒฝ์ฐ ์ค๋ฅ
pop_ch = pop(&s);
if ((pop_ch == '(' && ch != ')') ||
(pop_ch == '[' && ch != ']') ||
(pop_ch == '{' && ch != '}'))
return 0;
}
break;
} // switch๋ฌธ ๋
} // for๋ฌธ ๋
if (!is_empty(&s)) return 0; // ์ค๋ฅธ์ชฝ ๊ดํธ ๋๊น์ง ์ค์บํ์ ๋ ์คํ์ ๋จ์์๋ ๊ฒฝ์ฐ ์ค๋ฅ
return 1; // ์ฑ๊ณตํ ๊ฒฝ์ฐ 1์ ๋ฆฌํด
}
int main(void) {
char* exp = "{(a+b)*k[2+3]}"; // ๊ดํธ ๊ฒ์ฌํ ์ฝ๋
int result = check_matching(exp);
if (result==0)
printf("์๋ชป๋ ๊ดํธ ์ฌ์ฉ์
๋๋ค.\n");
else
printf("์ฌ๋ฐ๋ฅธ ๊ดํธ ์ฌ์ฉ์
๋๋ค.\n");
return 0;
}
๐ฅ switch ~ case๋ฌธ์ intํ์ด๋ charํ ๋ณ์๋ง ๊ฒ์ฌํ ์ ์์
์ค๋๋ง์ C์ธ์ด ์ฐ๋๊น "", '' ๊ตฌ๋ณ์ํด์ case "(" ์ด๋ ๊ฒ ์ฐ๊ณ ์ค๋ฅ๋ฌ์๋ค...