Upload files to "DS/C/Lab/Week3"
This commit is contained in:
parent
c23e09cb90
commit
a033c5175f
4 changed files with 194 additions and 0 deletions
51
DS/C/Lab/Week3/Parenthesis.c
Normal file
51
DS/C/Lab/Week3/Parenthesis.c
Normal file
|
@ -0,0 +1,51 @@
|
|||
#include <stdio.h>
|
||||
#define MAX_SIZE 100
|
||||
|
||||
char stack[MAX_SIZE];
|
||||
int top = -1;
|
||||
|
||||
void push(char c) {
|
||||
if (top < MAX_SIZE - 1) {
|
||||
stack[++top] = c;
|
||||
}
|
||||
}
|
||||
|
||||
char pop() {
|
||||
if (top >= 0) {
|
||||
return stack[top--];
|
||||
}
|
||||
return '\0';
|
||||
}
|
||||
|
||||
int is_matching_pair(char opening, char closing) {
|
||||
return (opening == '(' && closing == ')') ||
|
||||
(opening == '[' && closing == ']') ||
|
||||
(opening == '{' && closing == '}');
|
||||
}
|
||||
|
||||
int are_parentheses_balanced(char expr[]) {
|
||||
int i;
|
||||
for (i = 0; expr[i] != '\0'; i++) {
|
||||
if (expr[i] == '(' || expr[i] == '[' || expr[i] == '{') {
|
||||
push(expr[i]);
|
||||
} else if (expr[i] == ')' || expr[i] == ']' || expr[i] == '}') {
|
||||
if (top == -1 || !is_matching_pair(pop(), expr[i])) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
return (top == -1);
|
||||
|
||||
int main() {
|
||||
char expr[MAX_SIZE];
|
||||
printf("Enter an expression: ");
|
||||
scanf("%s", expr);
|
||||
|
||||
if (are_parentheses_balanced(expr)) {
|
||||
printf("Parentheses are balanced\n");
|
||||
} else {
|
||||
printf("Parentheses are not balanced\n");
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue