前端之家收集整理的这篇文章主要介绍了
【数据结构】用栈检测括号是否匹配,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
//【数据结构】用栈检测括号是否匹配
//头文件 栈
#ifndef _STACK_
#define _STACK_
#include <iostream>
#include <string.h>
using namespace std;
template <class Type>
class Stack
{
public:
Stack(size_t sz = INIT_SIZE)
{
capacity = sz > INIT_SIZE ? sz : INIT_SIZE;
base = new Type[capacity];
top = 0;
}
~Stack()
{
destory();
}
public:
bool empty() const //判断是否为空
{
return(top == 0);
}
bool full()const //判断是否已满
{
return(top >= capacity);
}
void push(const Type &x) //进栈
{
if (full())
{
cout << "栈已满,不能插入。" << endl;
return;
}
base[top++] = x;
}
void pop() //出栈
{
top--;
}
bool getTop(Type &x) const //获得栈顶
{
if (top == 0)
return false;
x = base[top - 1];
return true;
}
int length() const //求大小
{
return top;
}
void clear() //清除
{
top = 0;
}
void destory() //摧毁
{
delete[]base;
base = NULL;
capacity = top = 0;
}
void show() const //显示
{
if (empty() == 1)
{
cout << "栈为空" << endl;
return;
}
for (int i = top - 1; i >= 0; i--)
{
cout << base[i] << endl;
}
}
private:
enum { INIT_SIZE = 8 };
Type *base;
int capacity;
int top;
};
#endif
//主函数
#include "Stack.h"
bool Check(const char *str)
{
Stack <char> st;
char val;
while (*str != '\0')
{
if (*str == ']')
{
st.getTop(val);
if (val == '[')
{
st.pop();
}
else
return false;
}
else if (*str == ')')
{
st.getTop(val);
if (val == '(')
{
st.pop();
}
else
return false;
}
else
st.push(*str);
str++;
}
return st.empty();
}
int main()
{
char *str = "[([()])()]";
bool flag = Check(str);
if (flag)
cout << "OK" << endl;
else
cout << "NO" << endl;
return 0;
}
<img src="http://img.blog.csdn.net/20150531230542022?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZG91ZG91d2ExMjM0/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />