728x90
๐ตํ์ํ๊ธฐ์ ๊ณ์ฐ ์กฐ๊ฑด
- ํผ์ฐ์ฐ์๋ง ์คํ์ push
- ์ฐ์ฐ์์ธ ๊ฒฝ์ฐ
- ํผ์ฐ์ฐ์ 2๊ฐ pop > ๊ณ์ฐ > ๊ณ์ฐ ๊ฒฐ๊ณผ push
- ์คํ์ ๋จ์์๋ ํผ์ฐ์ฐ์ pop > ์ด ๊ฒฐ๊ณผ
๐กํ์ํ๊ธฐ์ ๊ณ์ฐ ์ฝ๋
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
typedef int 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 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 eval(char exp[]) {
int n = strlen(exp);
int op1, op2;
char c;
StackType s;
init(&s);
for (int i = 0; i < n; i++) {
c = exp[i];
if (c == '*' || c == '+' || c == '-' || c == '/') { // ์ฐ์ฐ์์ธ ๊ฒฝ์ฐ
op2 = pop(&s);
op1 = pop(&s);
switch (c) {
case '*': push(&s, op1 * op2); break;
case '+': push(&s, op1 + op2); break;
case '-': push(&s, op1 - op2); break;
case '/': push(&s, op1 / op2); break;
}
}
else{
push(&s, c - '0');
}
}
return pop(&s); // ์คํ์ ๋จ์์๋ ๊ฒฐ๊ณผ๊ฐ pop
}
int main() {
int result;
result = eval("82/3-32*+");
printf("ํ๊ธฐํ๊ธฐ์ ๊ณ์ฐ๊ฐ %d\n", result);
return 0;
}
๐ต ๋ฌธ์์ด ์ซ์ ์ ์ํ์ผ๋ก ๋ฐ๊พธ๊ธฐ
- atoi() ํจ์ ์ด์ฉํ๊ธฐ
char c = "123";
int i = atoi(c);
printf("%d\n", i); // ์ ์ํ 123
- ์์คํค์ฝ๋ ์ด์ฉํ๊ธฐ
char c = "123";
int i = c - '0';
printf("%d\n", i); // ์ ์ํ 123
๋ฌธ์ 0์ ์์คํค ์ฝ๋๋ 48, ๋ฌธ์ 1์ ์์คํค์ฝ๋๋ 49
> '1' - '0' ์ 1์ด ๋จ
- ๊ทธ ๋ฐ๋์ ๊ฒฝ์ฐ
C์์ ์ ์๋ฅผ Char๋ก ๋ณํ
์ด ํํ ๋ฆฌ์ผ์์๋ ์ ์๋ฅผ C ๋ฌธ์๋ก ๋ณํํ๋ ๋ค์ํ ๋ฐฉ๋ฒ์ ์๊ฐํฉ๋๋ค.
www.delftstack.com
'Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[C์ธ์ด] - ์ํ ํ Circular Queue (0) | 2023.01.11 |
---|---|
[C์ธ์ด] - ํ Queue (0) | 2023.01.11 |
[C์ธ์ด] Stack ์คํ - ์ค์ํ๊ธฐ์ infix์์ ํ์ํ๊ธฐ์ postfix์ผ๋ก ๋ณํ (0) | 2022.12.23 |
[C์ธ์ด] Stack ์คํ - ๊ดํธ ๊ฒ์ฌ (0) | 2022.12.13 |
[C์ธ์ด] Stack ์คํ - ๋์ ๋ฐฐ์ด ์คํ / ๋์ ๋ฉ๋ชจ๋ฆฌ ํ ๋น malloc, realloc, free (0) | 2022.12.13 |