Answer to Question #252532 in C for Svk

Question #252532
Write a C Program to implement balanced parenthesis.
1
Expert's answer
2021-10-18T00:14:39-0400
#include <stdio.h>
#include <stdlib.h>
#define bool int
struct Node {
	char d;
	struct Node* nxt;
};
void push(struct Node** top_ref, int new_data)
{
	struct Node* new_node
		= (struct Node*)malloc(sizeof(struct Node));


	if (new_node == NULL) {
		printf("Overflow");
		getchar();
		exit(0);
	}
	new_node->d = new_data;
	new_node->nxt = (*top_ref);
	(*top_ref) = new_node;
}
int pop(struct Node** top_ref)
{
	char res;
	struct Node* top;
	if (*top_ref == NULL) {
		printf("Overflow");
		getchar();
		exit(0);
	}
	else {
		top = *top_ref;
		res = top->d;
		*top_ref = top->nxt;
		free(top);
		return res;
	}
}


bool is_matching_pair(char c1, char c2)
{
	if (c1 == '(' && c2 == ')')
		return 1;
	else if (c1 == '{' && c2 == '}')
		return 1;
	else if (c1 == '[' && c2 == ']')
		return 1;
	else
		return 0;
}


bool are_balanced(char expression[])
{
	int i = 0;


	struct Node* stack = NULL;


	while (expression[i])
	{
		if (expression[i] == '{' || expression[i] == '(' || expression[i] == '[')
			push(&stack, expression[i]);


		if (expression[i] == '}' || expression[i] == ')'
			|| expression[i] == ']') {
			if (stack == NULL)
				return 0;


			else if (!is_matching_pair(pop(&stack), expression[i]))
				return 0;
		}
		i++;
	}
	if (stack == NULL)
		return 1; 
	else
		return 0; 
}


int main()
{
	char expression[100] = "(({()}[])";
	if (are_balanced(expression))
		printf("Balanced \n");
	else
		printf("Not Balanced \n");
	return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS