利用栈解决括号匹配和逆波兰表达式

当我们学习了栈这种数据结构滞后,我们就可以利用栈来解决一些实际问题。

这里是我们给出的动态顺序栈的实现

template< class T>
class Stack
{
public:
	Stack()
		:_array(new T[3])
		, _size(0)
		, _capacity(3)
	{}
	void Push(const T& data)
	{
		_Checkcapacity();
		_array[_size++] = data;

	}
	void Pop()
	{
		_size--;
	}

	bool Empty()
	{
		if (_size == 0)
			return true;
		return false;
	}
	T& Top()
	{
		return _array[_size-1];
	}
	T& Top()const
	{
		return _array[_size - 1];
	}
	size_t  Size()
	{
		return _size;
	}
	size_t Capacity()
	{
		return _capacity;
	}
	void  _Checkcapacity()
	{
		if (_size >= _capacity)
		{
			T* newarray = new T[_size * 2 + 3];
			for (int i = 0; i < _size; i++)
			{
				newarray[i] = _array[i];
			}
			_capacity = _size * 2 + 3;
			delete _array;
			_array = newarray;
		}
		 
	}
	~Stack()
	{
		if (_array)
			delete _array;
		_array = NULL;
		_size = 0;
		_capacity = 0;
	}
private:
	T * _array;
	int _size;
	int _capacity;
};

1.括号匹配问题

char a[] = "(())abc{[(])}";//左右括号次序不对
char b[] = "(()))abc{[]}";//右括号多于左括号
char c[] = "(()()abc{[]}";//左括号多于右括号
char d[] = "(())abc{[]()}";///左右括号正确

bool MatchBrackets(char* c,int size)
{
 Stack ch;
 for (int i = 0; i < size; i++)
 {
  if (c[i] == '(' || c[i] == '{' || c[i] == '[')
  {
   ch.Push(c[i]);
   continue;
  }
  else if (c[i] == ')' || c[i] == ']' || c[i] == '}')
  {
   if (ch.Empty())
   {
    cout << "右括号多于左括号" << endl;
    return true;
   }
   else
   {
    if ((c[i]==')'&&ch.Top()=='(')||(c[i] == ']'&&ch.Top() == '[')|| (c[i] == '}'&&ch.Top() == '{'))
    {
     ch.Pop();
     continue;
    }
    else {
     cout << "左右括号匹配次序不正确" << endl;
     return false;
    }
   }

  }
  else {
   continue;
  }
 }
 if (ch.Empty())
 {
  cout << "匹配正确" << endl;
  return true;
 }
 else {
  cout << "左括号多于右括号" << endl;
  return false;
 }

}

2.逆波兰表达式问题

利用栈解决括号匹配和逆波兰表达式_第1张图片

实现代码:

enum op { OPERAND,OPERATOR, ADD, SUB, MUL, DIV };
typedef struct Cell{
	op _op;
	int data;
	 
}Cell;
int RPN(Cell*s, int size)
{
	Stack c;
	for (int i = 0; i < size; i++)
	{
		if (s[i]._op == OPERAND)
		{
			c.Push(s[i].data);
			continue;
		}
		else if (s[i]._op == OPERATOR)
		{
			int right = c.Top();
			c.Pop();
			int left = c.Top();
			c.Pop();
			switch (s[i].data)
			{
			case ADD:
				c.Push(left + right);
				break;
			case SUB:
				c.Push(left - right);
				break;
			case MUL:
				c.Push(left*right);
				break;
			case DIV:
				assert(right != 0);
				c.Push(left / right);
				break;
				
			default:
				assert(0);
				break;
			}

		}
	}


	return c.Top();
}

下面我们给出 表达式:

Cell A[] = { {OPERAND,12},{OPERAND,3},{OPERAND,4},{OPERATOR,ADD},{OPERATOR,MUL},{OPERAND,6},{OPERATOR,SUB},{OPERAND,8},{OPERAND,2},{OPERATOR,DIV},{OPERATOR,ADD} };

即 表达式 12*(3+4)-6+8/2  =82;

来看程序运行结果:

利用栈解决括号匹配和逆波兰表达式_第2张图片

结果正确。




你可能感兴趣的:(c++)