Skip to content

Instantly share code, notes, and snippets.

@theabbie
Created July 20, 2020 09:17
Show Gist options
  • Save theabbie/62de2832092562b615dd3b02f51f952d to your computer and use it in GitHub Desktop.
Save theabbie/62de2832092562b615dd3b02f51f952d to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
void main() {
int top = -1;
int MAX = 10;
int flag = 1;
char stack[MAX];
char str[MAX];
void push(char x)
{
if (top >= MAX)
{
printf("Stack Overflow");
return;
}
top++;
stack[top] = x;
}
char pop()
{
if (top < 0) {
printf("Stack underflow");
return 0;
}
return stack[top--];
}
printf("Enter the Expression");
gets(str);
for (int i = 0; i < strlen(str); i++) {
if (str[i] == '(' || str[i] == '{' || str[i] == '[') push(str[i]);
if (str[i] == ')' || str[i] == '}' || str[i] == ']') {
if (top == -1) {
flag = 0;
}
else {
char temp = pop();
if (str[i] == ')' && (temp == '[' || temp == '{')) flag = 0;
if (str[i] == '}' && (temp == '(' || temp == '[')) flag = 0;
if (str[i] == ']' && (temp == '(' || temp == '{')) flag = 0;
}
}
}
if (top != -1) flag = 0;
if (flag == 1) printf("%s is a valid expression", str);
else printf("%s is an invalid expression", str);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment