您的位置:首页 > 编程语言 > C语言/C++

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

2015-04-30 15:34 519 查看
要匹配形如(((.....))这样的括号不匹配的,就可以将(入栈,然后当匹配到正确的)时候就出栈

具体代码如下:

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;
}


以上代码就完成了对括号的匹配,但是程序有个问题,就是当右边括号多余左边括号的时候就会出现内存泄露了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ 算法