Hello,
I have this assignment
For this assignment, write a program that uses a single stack to check whether a string containing braces, parentheses, and brackets is properly delimited.
Then, write another program that uses a single queue to check whether a string containing braces, parentheses, and brackets is properly delimited.
Please note that two separate programs will be submitted. One using a stack and the other using a queue.
This is the code I have and there are a few errors and I'm not sure how to fix any of this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
|
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
//Function to check if parenthesis is balanced
bool areParenthesisBalanced(string expr)
{
stack <char> s;
char x;
//Traversing the expression
for (int i = 0; i < expr.length(); i++)
{
if (expr[i] == '(' || expr[i] == '[' || expr[i] == '{')
{
//Push the element into the stack
s.push(expr[i]);
continue;
}
//If current character is not opening the stack, then it must be closed and empty
if (s.empty())
return false;
switch (expr[i])
{
case ')';
//Store the top element in a
x = s.top();
s.pop();
if (x == '{' || x == '[')
return false;
break;
case'}';
//Store the top element in b
x = s.top();
s.pop();
if (x == '(' || x == '[')
return false;
break;
case ']';
//Store the top element in c
x = s.top();
s.pop();
if (x == '(' || x == '{')
return false;
break;
}
}
//Check empty stack
retrun(s.empty());
}
};
|
This is the 2nd program i have
#include <iostream>
using namespace std;
char findClosing(char c)
{
if (c == '(')
return ')';
if (c == '{')
return '}';
if (c == '[')
return ']';
return -1;
}
//function to check to see if parenthesis is balanced
bool check(char expr[], int n)
{
//bases case
if (n == 0)
return true;
if (n == 1)
return false;
if (expr[0] == ')' || expr[0] == '}' || expr[0] == ']')
return false;
//search for closing bracker for first opening bracker
char closing = findClosing(expr[0]);
int i, count = 0;
for (i = 1; i < n; i++) {
if (expr[i] == expr[0])
count++;
if (expr[i] == closing) {
if (count == 0)
break;
count--;
}
}
}
//IF we don't find a closing bracket
if (i == n)
return false;
//if closing bracket was next to open
if (i == 1)
return check(expr + 2, n - 2);
if closing bracket is in the middle
return check(expr + 1, i - 1) && check(expr + i + 1, n - i - 1);
}
int main() {
char expr[] = "[(]";
int n = strlen(expr);
if (check(expr, n))
cout << "Balanced";
else
cout << "Not balanced";
return 0;
}