利用棧解決括號匹配和逆波蘭表達式

當我們學習了棧這種數據結構滯後,我們就可以利用棧來解決一些實際問題。

這裏是我們給出的動態順序棧的實現

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<char> 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.逆波蘭表達式問題

實現代碼:

enum op { OPERAND,OPERATOR, ADD, SUB, MUL, DIV };
typedef struct Cell{
	op _op;
	int data;
	 
}Cell;
int RPN(Cell*s, int size)
{
	Stack<int> 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;

來看程序運行結果:

結果正確。




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章