find the validity of first brackets
unknown
c_cpp
2 years ago
2.2 kB
9
Indexable
#include <stdio.h>
#include <stdlib.h>
// Structure to represent a stack
struct Stack {
char* array;
int top;
};
// Function to initialize an empty stack
void initializeStack(struct Stack* stack, int size) {
stack->array = (char*)malloc(size * sizeof(char));
stack->top = -1;
}
// Function to check if the stack is empty
int isEmpty(struct Stack* stack) {
return (stack->top == -1);
}
// Function to push a character onto the stack
void push(struct Stack* stack, char ch) {
stack->array[++stack->top] = ch;
}
// Function to pop a character from the stack
char pop(struct Stack* stack) {
if (!isEmpty(stack)) {
return stack->array[stack->top--];
}
return '\0'; // Return null character for an empty stack
}
// Function to check the validity of brackets
int isValidBrackets(char* expression) {
struct Stack stack;
initializeStack(&stack, 100); // Assuming a maximum size of 100 for the stack
for (int i = 0; expression[i] != '\0'; i++) {
char currentChar = expression[i];
if (currentChar == '(' || currentChar == '[' || currentChar == '{') {
push(&stack, currentChar);
} else if (currentChar == ')' || currentChar == ']' || currentChar == '}') {
if (isEmpty(&stack)) {
return 0; // Unmatched closing bracket
}
char poppedChar = pop(&stack);
// Check if the popped bracket matches the current closing bracket
if ((currentChar == ')' && poppedChar != '(') ||
(currentChar == ']' && poppedChar != '[') ||
(currentChar == '}' && poppedChar != '{')) {
return 0; // Mismatched opening and closing brackets
}
}
}
// Check if there are any unmatched opening brackets left in the stack
return isEmpty(&stack);
}
// Main function to test bracket validity
int main() {
char expression[100];
printf("Enter a sequence of brackets: ");
scanf("%s", expression);
if (isValidBrackets(expression)) {
printf("The brackets are valid.\n");
} else {
printf("The brackets are not valid.\n");
}
return 0;
}Editor is loading...
Leave a Comment