- 수학공식이나 문장을 쓰는데서 소괄호를 사용할 경우 각 괄호의 짝이 맞는지를 스택을 이용해서 체크해주는 코드
- input: (a+b)*(c-d)
- output: 괄호가 열리고 닫히는 각각의 위치를 출력하고 짝이 맞지 않을 경우 에러 출력
- output 예제

Makefile
//check parenthesis
//error output, if number of left '(' and right ')' are differnet.
//main.cpp
#include <iostream>
#include <cstring>
using namespace std;
template <class T>
class Stack
{
private:
T*array_stack;
int list_size;
int stack_size;
public:
Stack() {
array_stack = new T[0];
list_size = 0;
stack_size = 0;
}
Stack(int length)
{
stack_size = length;
list_size = 0;
array_stack = new T[length];
}
Stack(T* arr, int size)
{
this->list_size = size;
stack_size = size;
array_stack = new T[list_size];
for (int i = 0; i < size; i++)
{
array_stack[i] = arr[i];
}
}
bool stack_empty() {
if (list_size == 0)
return true;
else
return false;
}
int max_size() {
return stack_size;
}
void erase(T* arr, int n)
{
for (int i = n - 1; i >= 0; i--)
{
arr[i + 1] = arr[i];
}
for (int i = 0; i < n; i++)
{
arr[i] = arr[i + 1];
}
this->list_size--;
}
T& top() {
if (stack_empty()) {
cout << "Stack is empty\\n";
}
return array_stack[list_size - 1];
}
void pop() {
if (stack_empty())
cout << "Stack is empty" << endl;
else
erase(array_stack, list_size);
}
void push(const T& element)
{
int size = max_size();
if (size <= list_size)
cout << "Full stack" << endl;
else {
array_stack[list_size] = element;
list_size++;
}
}
void show()
{
for (int i = 0; i < list_size; i++) {
cout << array_stack[i] << " ";
}
cout << endl;
cout << "list size: " << list_size << endl;
cout << "stack size: " << stack_size << endl;
}
};
#include "Parenthesis_checking.hpp"
#include "main.cpp"
void Parenthesis(string exp)
{
int length = (int)exp.size();
Stack<int> s(length);
int error_check = 0;
//scan string exp
for (int i = 0; i < length; i++)
{
if (exp.at(i) == '(')
s.push(i);
else
if (exp.at(i) == ')'&&s.stack_empty() != true)
{
cout << s.top() << " : " << i << endl;
s.pop();
}
else if (exp.at(i) == ')' && s.stack_empty() == true)
{
error_check++;
break;
}
}
//remaining check
if (error_check != 0)
{
cout << "remain ')' check again!!" << endl;
}
else if (!s.stack_empty()) {
while (!s.stack_empty())
{
cout << "No macth for left parenthesis at " << s.top() << endl;
s.pop();
}
}
else
cout << "No Error!! Everything is OK" << endl;
}
int main()
{
string s;
cout<<"Input expression: ";
cin>>s;
Parenthesis(s);
return 0;
}