This C++ program, using a stack data strucure, computes whether the given parantheses expression is valid or not by checking whether each parentheses is closed and nested in the input expression.
Here is the source code of the C++ program to display if it is a balanced expreesion or an invalid string. This C++ program is successfully compiled and run on DevCpp, a C++ compiler. The program output is given below.
/*
* C++ Program to Check for balanced paranthesis by using Stacks
*/
#include <iostream>
#include <conio.h>
using namespace std;
struct node
{
char data;
node *next;
}*p = NULL, *top = NULL, *save = NULL,*ptr;
void push(char x)
{
p = new node;
p->data = x;
p->next = NULL;
if (top == NULL)
{
top = p;
}
else
{
save = top;
top = p;
p->next = save;
}
}
char pop()
{
if (top == NULL)
{
cout<<"underflow!!";
}
else
{
ptr = top;
top = top->next;
return(ptr->data);
delete ptr;
}
}
int main()
{
int i;
char c[30], a, y, z;
cout<<"enter the expression:\n";
cin>>c;
for (i = 0; i < strlen(c); i++)
{
if ((c[i] == '(') || (c[i] == '{') || (c[i] == '['))
{
push(c[i]);
}
else
{
switch(c[i])
{
case ')':
a = pop();
if ((a == '{') || (a == '['))
{
cout<<"invalid expr!!";
getch();
}
break;
case '}':
y = pop();
if ((y == '[') || (y == '('))
{
cout<<"invalid expr!!";
getch();
}
break;
case ']':
z = pop();
if ((z == '{') || (z == '('))
{
cout<<"invalid expr!!";
getch();
}
break;
}
}
}
if (top == NULL)
{
cout<<"balanced expr!!";
}
else
{
cout<<"string is not valid.!!";
}
getch();
}
Output
enter the expression:
[{{{}}}{{()[[]]}}]
balanced expr!!
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
If you wish to look at all C++ Programming examples, go to C++ Programs.
Next Steps:
- Get Free Certificate of Merit in Data Structure I
- Participate in Data Structure I Certification Contest
- Become a Top Ranker in Data Structure I
- Take Data Structure I Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Buy Programming Books
- Apply for Computer Science Internship
- Buy Data Structure Books
- Buy Computer Science Books
- Practice Programming MCQs
advertisement
advertisement
Additional Resources: