现在的位置: 首页 > 综合 > 正文

括号匹配

2013年07月29日 ⁄ 综合 ⁄ 共 1579字 ⁄ 字号 评论关闭
#include <iostream>
#include <string>
using namespace std;
template <class T>
class node
{
public:
	node<T>* next;
	T val;
	node():next(NULL),val(){};
	node(T v):next(NULL),val(v){};
};
template <class T>
class my_stack
{
public:
	my_stack();
	~my_stack();
	void init_stack();
	bool is_empty();
	size_t get_len();
    T* get_top();
	T get_top_val();
	void push(const T& e);
    void pop();
	void display();
private:
    node<T>* top;
    size_t len;
};
template <class T>
my_stack<T>::my_stack()
{
   top  = NULL;
   len = 0;
}
template <class T>
my_stack<T>::~my_stack()
{
	node<T>* pre = top;
	if (top)
	{
       delete top;
	   top = pre->next;
	   pre = pre->next;
	}
	len = 0;
}
template <class T>
bool my_stack<T>::is_empty()
{
	return len == 0;
}
template <class T>
size_t my_stack<T>::get_len()
{
	return len;
}
template <class T>
T my_stack<T>::get_top_val()
{
   return top->val;
}
template <class T>
void my_stack<T>::push(const T& e)
{
   node<T>* tmp = new node<T>(e);
   if (top == NULL)
   {
	   top =tmp;
   }
   else
   {
	   tmp->next = top;
	   top = tmp;
   }
   ++len;
}
template <class T>
T* my_stack<T>::get_top()
{
	return top;
}
template <class T>
void my_stack<T>::pop()
{
	if(is_empty())
		throw new exception("The stack is empty!");
    if (len ==1)
    {
		top  = NULL;
    }
	else
	{
        node<T>* tmp = top;
        top = top->next;
		delete tmp;
	}
	--len;
   
}
template <class T>
void my_stack<T>::display()
{
   node<T>* pre = top;
   cout << "The stack is: ";
   while(pre)
   {
	   cout << pre->val << " ";
	   pre = pre->next;
   }
   cout << endl;
}
void char_mach(string s)
{
	size_t len = s.size();
	my_stack<char> sq;
	for (size_t i = 0; i != len; ++i)
	{
	   if (s[i]=='[' || s[i]=='(')
		   sq.push(s[i]);
	   else
	   {
		   if (s[i] == ']')
	          if (sq.get_top_val() == '[')
	               sq.pop();
	          else
	             throw new exception("Not match!");
		   else
			   if (s[i] == ')')
				   if (sq.get_top_val() == '(')
					   sq.pop();
				   else
					   throw new exception("Not match!");
	   }
	}
	cout << "match well" << endl;
}
int main()
{
   string s;
   cout << "输入表达式:"<<endl;
   cin >> s;
   char_mach(s);
}

抱歉!评论已关闭.