利用栈实现括号匹配检测

利用栈实现括号匹配检测

Description

在一个字符串中检验左右括号是否匹配,其中括号有3种,分别为圆括号“( )”,方括号“[ ]”和花括号“{ }”,要求字符串中括号必须成对出现,且圆括号、方括号、花括号对应匹配。要求:该括号匹配函数不属于类的成员函数,定义一个独立的函数,通过使用顺序栈的成员函数实现。

Input

输入一行字符串

Output

输出匹配结果,匹配成功输出“success”,匹配失败输出“failure”。

Sample Input

{a*[b/(c+d)]}

Sample Output

success

HINT

输出数据都用cout, 不要使用课件中例子里的 cerr

其他测试数据:

Input: {a*[b/(c+d]}) Output: failure

Input: {a*[b/(c+d)]}] Output: failure

代码如下:

#include<iostream>

using namespace std;

template<class T>
struct StackNode
{
	T data;
	StackNode<T>* link;
	StackNode()
	{
		link = NULL;
	}
	StackNode(T x)
	{
		data = x;
		link = NULL;
	}
};

template<class T>
class Stack
{
public:
	Stack();  //构造函数
	~Stack();  //析构函数
	void Push(T x);  //入栈
	bool Pop(T& x);  //出栈
	bool Get_top(T& x)const;  //取栈顶值
	void MakeEmpty();  //清空栈
	bool IsEmpty(); //判断栈空
private:
	StackNode<T>* top;
};

template<class T>
Stack<T>::Stack()
{
	top = NULL;
}

template<class T>
Stack<T>::~Stack()
{
	MakeEmpty();
}

template<class T>
void Stack<T>::Push(T x)
{
	StackNode<T>* newnode;
	newnode = new StackNode<T>(x);
	if (newnode == NULL)
		return;
	newnode->link = top;
	top = newnode;
}

template<class T>
bool Stack<T>::Pop(T& x)
{
	StackNode<T>* temp = NULL;
	if (top == NULL)
		return false;
	temp = top;
	top = top->link;
	x = temp->data;
	delete temp;
	return true;
}

template<class T>
bool Stack<T>::Get_top(T& x)const
{
	if (top == NULL)
		return false;
	x = top->data;
	return true;
}

template<class T>
void Stack<T>::MakeEmpty()
{
	T temp;
	while (Pop(temp));
}

template<class T>
bool Stack<T>::IsEmpty()
{
	if (top == NULL)
		return true;
	else
		return false;
}

bool Match()  //括号匹配
{
	Stack<char> t;
	char ch,temp,top_data;
	while (cin >> noskipws >> ch && ch != '\n')
	{
		if (ch == '(' || ch == '[' || ch == '{')
		{
			t.Push(ch);
		}
		else
		{
			if (t.Get_top(top_data))
			{
				if (ch == ')' && top_data == '(' || ch == ']' && top_data == '[' || ch == '}' && top_data == '{')
				{
					t.Pop(temp);
				}
			}
			else
			{
				if (ch == ')' || ch == ']' || ch == '}')
					return false;
			}
		}
	}
	return t.IsEmpty();
}

int main()
{
	if (Match())
		cout << "success" << endl;
	else
		cout << "failure" << endl;
	return 0;
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值