728x90
๐ต infix -> postfix ๋ณํ ์กฐ๊ฑด
- ์คํ์ ์ฐ์ฐ์๋ง push
- ๊ดํธ์ธ ๊ฒฝ์ฐ
- ์ผ์ชฝ ๊ดํธ๋ ๋ฌด์กฐ๊ฑด ์คํ์ push
- ์ค๋ฅธ์ชฝ ๊ดํธ์ธ ๊ฒฝ์ฐ ์ผ์ชฝ๊ดํธ ์ญ์ ๋ ๋๊น์ง ์์ ์์ธ ์ฐ์ฐ์ pop
- ๊ดํธ๊ฐ ์๋ ๊ฒฝ์ฐ (+, -, *, /)
- ์ฐ์ฐ์ ์ฐ์ ์์ ๋น๊ตํ๊ธฐ
- ์คํ์ ๋ค์ด์๋ ์ฐ์ฐ์ ์ฐ์ ์์๊ฐ ๋ ํฐ ๊ฒฝ์ฐ ํด๋น ์ฐ์ฐ์ pop
- ๊ดํธ์ธ ๊ฒฝ์ฐ
๐ก ์ค์ํ๊ธฐ์ ํ์ํ๊ธฐ์์ผ๋ก ๋ณํํ๋ ์ฝ๋
#include <stdio.h>
#include <stdlib.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, char c) {
if (is_full(s)) {
printf("์คํ์ด ๊ฐ๋์ฐผ์ต๋๋ค.\n");
return;
}
else {
s->data[++(s->top)] = c;
}
}
char pop(StackType* s) {
if (is_empty(s)) {
printf("์คํ์ด ๋น์์ต๋๋ค.\n");
return;
}
else {
return s->data[(s->top)--];
}
}
char peek(StackType* s) {
return s->data[(s->top)];
}
// ์ฐ์ฐ์ ์ฐ์ ์์ ํ์ธํ๊ธฐ
int check_priority(char c) {
switch (c) {
case '(': case ')': return 0;
case '+': case '-': return 1;
case '*': case '/': return 2;
}
}
// ์ค์ํ๊ธฐ์์ ํ์ํ๊ธฐ์์ผ๋ก ๋ณํ
void infix_to_postfix(char exp[]) {
char c, top_c;
int i, n = strlen(exp);
StackType s;
init(&s); // ์คํ ์ด๊ธฐํ
for (i = 0; i < n; i++) {
c = exp[i];
switch (c) {
case '(': // ์ผ์ชฝ ๊ดํธ์ธ ๊ฒฝ์ฐ
push(&s, c);
break;
case ')': // ์ค๋ฅธ์ชฝ ๊ดํธ์ธ ๊ฒฝ์ฐ
top_c = pop(&s);
while (top_c != '(') {
printf("%c", top_c);
top_c = pop(&s);
}
break;
case '+': case '-': case '*': case '/': // ๊ดํธ๊ฐ ์๋ ์ฐ์ฐ์์ ๊ฒฝ์ฐ
while (!is_empty(&s) && check_priority(peek(&s)) >= check_priority(c)) { // ์คํ ์์ ๋ค์ด์๋ ์ฐ์ฐ์์ ์ฐ์ ์์๊ฐ ๋ ๋์ ๊ฒฝ์ฐ pop
printf("%c", pop(&s));
}
push(&s, c);
break;
default: // ํผ์ฐ์ฐ์
printf("%c", c);
break;
}
}
while (!is_empty(&s)) {
printf("%c", pop(&s));
}
}
int main(void) {
char* s = "(a+b)*c";
printf("์ค์ํ๊ธฐ์ : %s\n", s);
printf("ํ์ํ๊ธฐ์ : ");
infix_to_postfix(s);
return 0;
}
'Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[C์ธ์ด] - ์ํ ํ Circular Queue (0) | 2023.01.11 |
---|---|
[C์ธ์ด] - ํ Queue (0) | 2023.01.11 |
[C์ธ์ด] Stack ์คํ - ํ์ํ๊ธฐ์ ๊ณ์ฐ postfix / ๋ฌธ์์ด ์ซ์ ์ ์ํ์ผ๋ก ๋ฐ๊พธ๊ธฐ (0) | 2023.01.11 |
[C์ธ์ด] Stack ์คํ - ๊ดํธ ๊ฒ์ฌ (0) | 2022.12.13 |
[C์ธ์ด] Stack ์คํ - ๋์ ๋ฐฐ์ด ์คํ / ๋์ ๋ฉ๋ชจ๋ฆฌ ํ ๋น malloc, realloc, free (0) | 2022.12.13 |