算法复习--------------利用堆栈实现括号匹配

要匹配形如(((.....))这样的括号不匹配的,就可以将(入栈,然后当匹配到正确的)时候就出栈


具体代码如下:

template<class T>
class Stack{
public:
	Stack(int MaxStackSize = 10);
	~Stack(){ delete[]stack; }
	bool IsEmpty() const{
		return top == -1;
	}

	bool IsFull()const{
		return top == MaxTop;
	}

	T Top()const;

	Stack<T> &Add(const T& x);
	Stack<T> & Delete(T& x);

private:
	int top;
	int MaxTop;
	T* stack;
};


template<class T>
Stack<T>::Stack(int MaxStackSize /* = 10 */){
	MaxTop = MaxStackSize - 1;
	stack = new T[MaxStackSize];
	top = -1;
}


template<class T>
T Stack<T>::Top()const{
	if (IsEmpty())throw;

	else
		return stack[top];
}

template<class T>
Stack<T>& Stack<T>::Add(const T& x)
{
	if (IsFull())throw;

	stack[++top] = x;
	return *this;
}


template<class T>
Stack<T>& Stack<T>::Delete(T& x)
{
	if (IsEmpty())throw;

	x = stack[top--];
	return *this;
}




// ClassStackTest.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "ClassStack.h"
#include <iostream>
#include <string>
#include <stdio.h>

using namespace std;

const int MaxLength = 100;

void PrintMatchedPairs(char* expr){
	Stack<int> s(MaxLength);

	int j, length = strlen(expr);

	for (int i = 0; i <= length; i++)
	{
		if (expr[i - 1] == '(')
			s.Add(i);
		else if (expr[i - 1] == ')')
		{
			try{
				s.Delete(j);
				cout <<"the matched is" <<j << ' ' << i << endl;
			}
			catch (...){
				cout << "No match for right parenthesis at" << i << endl;
			}

		}

	}

	while (!s.IsEmpty())
	{
		s.Delete(j);
		cout << "no match for left parentsthesis at " << j << endl;
	}

}

int _tmain(int argc, _TCHAR* argv[])
{
	char expr[MaxLength];
	cout << " type an expression of length at most " << MaxLength << endl;
	cin.getline(expr, MaxLength);
	cout << "the [pairs of matching parenthess in " << endl;
	puts(expr);
	cout << "are" << endl;
	PrintMatchedPairs(expr);

	getchar();
	getchar();
	return 0;
}


以上代码就完成了对括号的匹配,但是程序有个问题,就是当右边括号多余左边括号的时候就会出现内存泄露了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值