I need help implementing part 2 of the problem below to the code I have from par
ID: 3731366 • Letter: I
Question
I need help implementing part 2 of the problem below to the code I have from part 1 below.
#include<bits/stdc++.h>
using namespace std;
#define MAX 1000
class Stack {
int top;
public:
int a[MAX]; // Max size of Stack
Stack() {
top = -1;
}
//top is initialized to -1 to check the emptiness of the stack
bool push(int x);
int pop();
bool isEmpty();
};
bool Stack::push(int x){
if (top >= MAX){
cout << "Stack is full it Overflowing";
return false;
}
else{
a[++top] = x;
return true;
}
}
int Stack::pop(){
if (top < 0){
cout << "Stack is Underflowing";
return 0;
}
else{
int x = a[top--];
return x;
}
}
//Checks the stack if its empty or not
bool Stack::isEmpty(){
return (top < 0);
}
// main pogram to check the functions
int main(){
struct Stack s;
s.push(20);
s.push(70);
s.push(10);
cout << s.pop() << " is Popped from our Stack ";
return 0;
}
Explanation / Answer
Since your stack can only store integer values, you can map each of the parenthesis to a number and store those numbers representing parenthesis.
Let's represent the opening parenthesis using positive numbers, and closing parenthesis using negative numbers.
{ = 1 } = -1
[ = 2 ] = -2
( = 3 ) = -3
If you encounter any opening parenthesis, simply insert the number corresponding to it in the stack.
If you encounter any closing parenthesis, pop from the stack and see if the absolute value of both the number matches or not.
If they don't match, then the parenthesis is not balanced
else, continue
If after the completion of the program if the stack is not empty then not balanced, else balanced.
I hope this will help you in writing your program.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.