Algorithm

[C์–ธ์–ด] Stack ์Šคํƒ - ๊ด„ํ˜ธ ๊ฒ€์‚ฌ

say! 2022. 12. 13. 17:22
728x90

๐Ÿ”ต ๊ด„ํ˜ธ ๊ฒ€์‚ฌ ์กฐ๊ฑด

  1. ์˜ค๋ฅธ์ชฝ ๊ด„ํ˜ธ ๋งŒ๋‚  ๋•Œ๊นŒ์ง€ ์™ผ์ชฝ ๊ด„ํ˜ธ push
  2. ์˜ค๋ฅธ์ชฝ ๊ด„ํ˜ธ ๋งŒ๋‚ฌ์„ ๊ฒฝ์šฐ
    1. ์Šคํƒ์— ๋“ค์–ด์žˆ๋Š” ์™ผ์ชฝ ๊ด„ํ˜ธ pop
    2. ๐Ÿ’ฅ์˜ค๋ฅ˜์ธ ๊ฒฝ์šฐ
      1. ์Šคํƒ์ด ๋น„์–ด์žˆ์„ ๋•Œ
      2. ๊ด„ํ˜ธ ์ข…๋ฅ˜๊ฐ€ ๋งž์ง€ ์•Š์„ ๋•Œ
  3. ์˜ค๋ฅธ์ชฝ ๊ด„ํ˜ธ ๋๊นŒ์ง€ ์Šค์บ”ํ–ˆ์„ ๊ฒฝ์šฐ
    1. ๐Ÿ’ฅ์˜ค๋ฅ˜์ธ ๊ฒฝ์šฐ
      1. ์Šคํƒ์ด ๋น„์–ด์žˆ์ง€ ์•Š์•˜์„ ๋•Œ

๐ŸŸก ๊ด„ํ˜ธ ๊ฒ€์‚ฌ ์ฝ”๋“œ

#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 "(" ์ด๋ ‡๊ฒŒ ์“ฐ๊ณ  ์˜ค๋ฅ˜๋‚ฌ์—ˆ๋‹ค...