코딩 이야기

[C언어] 스택(stack)을 이용하여 수식의 괄호 쌍 검사

고주망고 2021. 11. 2. 09:06

안녕하세요 이번 포스팅에서는 스택을 이용하여 괄호 쌍 검사하는 프로그램을 구현 해보겠습니다

( { [ 를 만나면 push(), ) } ]를 만나면 pop()하여 쌍이 맞는지를 검사하는 아주 간단한 프로그램입니다.

 

평등한 경우
평등하지않은경우(*4앞에 ]가 없음)

 

가장 늦게 열리는 괄호가 가장 빨리 닫힌다는 점을 이용(=스택의 선입선출 구조) 한 프로그램 입니다.


#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef int element;

typedef struct stackNode {
	element data;
	struct stackNode* link;
}stackNode;

stackNode* top;

void push(int item) {
	stackNode* newNode = (stackNode*)malloc(sizeof(stackNode));
	newNode->data = item;
	newNode->link = top;
	top = newNode;
}

element pop() {
	stackNode* temp;
	temp = top->data;
	top = top->link;
	return temp;
}

int testpair(char* exp) {
	char symbol, open_pair;
	int i, length = strlen(exp);
	top = NULL;

	for (i = 0; i < length; i++) {
		symbol = exp[i];
		switch (symbol) {
		case '(':
		case '[':
		case '{':
			push(symbol);
			break;
		case ')':
		case ']':
		case '}':
			if (top == NULL) {
				return 0;
			}
			else {
				open_pair = pop();
				if ((open_pair == '(') && (symbol == ')') || (open_pair == '[') && (symbol == ']') || (open_pair == '{') && (symbol == '}')) {
					break;
				}
				else {
					return 0;
				}
			}
		}
	}
	if (top == NULL) return 1; //전부 수행하고 리스트가 빈 경우
	else return 0;
}

void main() {
	char* express = "{(A+B)-3}*5+[{cos(x+y)+7}-1]*4";

	printf("{(A+B)-3}*5+[{cos(x+y)+7}-1]*4의 괄호는 평등한가 ? \n");
	if (testpair(express)) {
		printf("괄호 개수는 평등합니다");
	}
	else {
		printf("괄호 개수는 평등하지않습니다");
	}

}