首页 > 代码库 > 括号匹配--栈

括号匹配--栈

#include <iostream>
using namespace std;
typedef char stackEntry;
const int maxstack = 100;//栈的最大尺寸
class stack{
public:
stack();
void pop();
void push(const stackEntry &item);
void top(stackEntry &item) const;
bool empty() const;
private:
int count;
stackEntry data[maxstack];
};

void stack::push(const stackEntry &item)//如果栈未满,将元素item压入栈顶,否则报错
{
if (count >= maxstack)
cout << "栈上溢,无法压入元素。";
else
data[count++] = item;
}

void stack::pop()//如果栈未空,将栈顶元素删除,否则报错
{
if (count == 0)
cout << "栈下溢,无法弹出元素。";
else
--count;
}

void stack::top(stackEntry &item) const//如果栈未空,将栈顶元素取出放在item里,否则报错
{
if (count == 0)
cout << "栈下溢,无法读取元素。";
else
item = data[count - 1];
}

bool stack::empty() const //判断栈是否为空
{
if (count > 0)
return false;
return true;
}

stack::stack()//构建函数,初始化一个空栈
{
count = 0;
}

int main()
{
stack openings;
char symbol;
bool match = true;
cout << "请输入一行带括号的文字:" << endl;
while (match && (symbol = cin.get()) != ‘\n‘){
if (symbol == ‘{‘ || symbol == ‘(‘ || symbol == ‘[‘)
openings.push(symbol);
if (symbol == ‘}‘ || symbol == ‘)‘ || symbol == ‘]‘)
if (openings.empty()){
cout << "检测到不匹配的右括号" << symbol << endl;
match = false;
system("pause");
return 0;
}
else
{
char topSymbol;
openings.top(topSymbol);
openings.pop();
match = (symbol == ‘}‘&&topSymbol == ‘{‘)
|| (symbol == ‘)‘&&topSymbol == ‘(‘)
|| (symbol == ‘]‘&&topSymbol == ‘[‘);
if (!match){
cout << "括号类型不匹配" << match << symbol << endl;
system("pause");
return 0;
}
}
}
if (!openings.empty())
{
cout << "检测到多余的左括号." << endl;
system("pause");
}
else
{
cout << "所有括号都完美匹配,谢谢!" << endl;
system("pause");
}
return 0;
}

括号匹配--栈