码迷,mamicode.com
首页 > 其他好文 > 详细

【数据结构】用栈检测括号是否匹配

时间:2015-06-01 09:47:32      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:   操作   数据结构   类模板   c++   

//【数据结构】用栈检测括号是否匹配

//头文件  栈
#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="" />


【数据结构】用栈检测括号是否匹配

标签:   操作   数据结构   类模板   c++   

原文地址:http://blog.csdn.net/doudouwa1234/article/details/46293369

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!