Algorithm

[C์–ธ์–ด] Stack ์Šคํƒ - ์ค‘์œ„ํ‘œ๊ธฐ์‹ infix์—์„œ ํ›„์œ„ํ‘œ๊ธฐ์‹ postfix์œผ๋กœ ๋ณ€ํ™˜

say! 2022. 12. 23. 17:43
728x90

๐Ÿ”ต infix -> postfix ๋ณ€ํ™˜ ์กฐ๊ฑด

  1. ์Šคํƒ์— ์—ฐ์‚ฐ์ž๋งŒ push 
    1. ๊ด„ํ˜ธ์ธ ๊ฒฝ์šฐ
      1. ์™ผ์ชฝ ๊ด„ํ˜ธ๋Š” ๋ฌด์กฐ๊ฑด ์Šคํƒ์— push
      2. ์˜ค๋ฅธ์ชฝ ๊ด„ํ˜ธ์ธ ๊ฒฝ์šฐ ์™ผ์ชฝ๊ด„ํ˜ธ ์‚ญ์ œ๋  ๋•Œ๊นŒ์ง€ ์œ„์— ์Œ“์ธ ์—ฐ์‚ฐ์ž pop
    2. ๊ด„ํ˜ธ๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ (+, -, *, /)
      1. ์—ฐ์‚ฐ์ž ์šฐ์„ ์ˆœ์œ„ ๋น„๊ตํ•˜๊ธฐ
      2. ์Šคํƒ์— ๋“ค์–ด์žˆ๋Š” ์—ฐ์‚ฐ์ž ์šฐ์„ ์ˆœ์œ„๊ฐ€ ๋” ํฐ ๊ฒฝ์šฐ ํ•ด๋‹น ์—ฐ์‚ฐ์ž 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;
}