括号匹配检验(栈)

括号匹配检验(栈)

示例:

eg1: {[(1+2)3+6]-29}*2-4
左右括号匹配
eg2: ( {[(1+2)3+6]-29}*2-4
左括号多余
eg3: ){[(1+2)3+6]-29}*2-4
右括号多余
eg4:(]{[(1+2)3+6]-29}*2-4
左右括号不匹配

运行结果如下:

运行结果1
运行结果2
运行结果3
运行结果4

源代码如下:

#include<iostream>
#include<string>
using namespace std;

class Node {
public:
	char ch;
	Node* next;
	Node(char c,Node *n=NULL):ch(c),next(n){}
	Node():next(NULL){}
};
class Stack{
public:
	Stack():top(NULL){}
	~Stack() { while (top != NULL) { Node* temp = top; top = top->next; delete temp; } }
	char gettop() { return top->ch; }
	bool Empty() { return top == NULL; }
	void push(char c);
	void pop(char& c);
private:
	Node* top;
};

void Stack::push(char c) {
	if (top == NULL) { top = new Node(c); return; }
	Node* p = new Node(c,top);
	top = p;
}

void Stack::pop(char &c) {
	if (top == NULL)	return;
	Node* p = top;
	top = top->next;
	c = p->ch;
	delete p;
}

void check(string &s){
	int n = s.size();
	Stack stack;
	for (int i = 0; i < n; i++) {
		if (s[i] == '(' || s[i] == '[' || s[i] == '{')	stack.push(s[i]);
		if (s[i] == ')' || s[i] == ']' || s[i] == '}') {
			if(stack.Empty())	{cout<<"右括号多余"<<endl;return;} 
			char ch = stack.gettop();
			if (s[i] == ')' && ch == '(')	stack.pop(ch);
			else if (s[i] == ']' && ch == '[')	stack.pop(ch);
			else if (s[i] == '}' && ch == '{')	stack.pop(ch);
			else 	{cout<<"左右括号不匹配"<<endl;return;} 
		}
	}
	if (stack.Empty()) cout << "括号匹配" << endl;
	else cout << "左括号多余" << endl;
}

int main() {
	string s("(][(1+2)*3+6]-2*9}*2-4");//待检验算术表达式s
	cout<<s<<endl;
	check(s);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值