-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackBalancedParentheses.cpp
More file actions
70 lines (62 loc) · 1.55 KB
/
StackBalancedParentheses.cpp
File metadata and controls
70 lines (62 loc) · 1.55 KB
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
61
62
63
64
65
66
67
68
69
70
/* Program: Balancing Symbols
Author: Aaron Lewis
Class: CSCI 220 MW
Date: 10/01/2017
Description: This program notifies a user if an
equation has balanced, appropriately placed
parentheses, braces and brackets.
I certify that the code below is my own work.
Exception(s): N/A
*/
#include <iostream>
#include <stack>
int main()
{
std::cout << "Author: Aaron Lewis\n\n";
// Create char var to hold next char in a string expression
char next;
// Assume expression starts as true
bool balanced = true;
// Create a stack to hold the parentheses, braces, and brackets
std::stack<char> symbols;
// Get user input expression until Q is entered
std::cout << "Input an expression, Q to stop input: ";
// Scan all characters until sentinel char Q is encountered or the expression is
// found to be unbalanced
while (std::cin >> next && balanced == true && next != 'Q')
{
if (next == ')')
{
if (symbols.empty() || symbols.top() != '(')
balanced = false;
else
symbols.pop();
}
else if (next == '}')
{
if (symbols.empty() || symbols.top() != '{')
balanced = false;
else
symbols.pop();
}
else if (next == ']')
{
if (symbols.empty() || symbols.top() != '[')
balanced = false;
else
symbols.pop();
}
else if (next == '(')
symbols.push(next);
else if (next == '{')
symbols.push(next);
else if (next == '[')
symbols.push(next);
}
// Print the results
if (balanced == true && symbols.empty())
std::cout << "The expression is balanced!\n";
else
std::cout << "The expression is not balanced!\n";
return 0;
}