MIT-Curricular/DS/C/Lab/Week3/Parenthesis.c

68 lines
1.2 KiB
C

#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100
int top = -1;
char stack[MAX_SIZE];
void push(char value) {
if (top == MAX_SIZE - 1) {
printf("Stack is full\n");
return;
}
stack[++top] = value;
}
char pop() {
if (top == -1) {
printf("Stack is empty\n");
return '\0';
}
return stack[top--];
}
int isMatching(char c1, char c2) {
if (c1 == '(' && c2 == ')')
return 1;
if (c1 == '[' && c2 == ']')
return 1;
if (c1 == '{' && c2 == '}')
return 1;
return 0;
}
int isParenthesisBalanced(char* expression) {
for (int i = 0; i < strlen(expression); i++) {
char c = expression[i];
if (c == '(' || c == '[' || c == '{')
push(c);
if (c == ')' || c == ']' || c == '}') {
char pop_value = pop();
if (!isMatching(pop_value, c))
return 0;
}
}
if (top == -1)
return 1;
else
return 0;
}
int main() {
char expression[MAX_SIZE];
printf("Enter an expression: ");
scanf("%s", expression);
if (isParenthesisBalanced(expression))
printf("Expression is balanced\n");
else
printf("Expression is not balanced\n");
return 0;
}