使用stack對象處理帶圓括號的表達式。

#include<iostream>
#include<stack>
#include<string>
using namespace std;

int main()
{
	stack<char> sstack;
	string str;

	cout << "please int string for str:" << endl;
	cin >> str;

	string::iterator iter = str.begin();
	while(iter != str.end())
	{
		if(*iter != ')')
			sstack.push(*iter);
		else
		{
			while(sstack.top() != '(' && !sstack.empty())
			{
				sstack.pop();
			}
			if(sstack.empty())
				cout << "parentheses are not matched" << endl;
			else 
			{
				sstack.pop();
				sstack.push('@');
			}

		}
		++iter;
	}

	while(sstack.empty() == false)
	{
		char value = sstack.top();
		cout << value << " ";
		sstack.pop();
	}

	return 0;
}

輸入輸出結果:



發佈了29 篇原創文章 · 獲贊 10 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章