题解 | 【模板】栈

【模板】栈

https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf

#include<iostream>
#include<vector>
#include<string>

using namespace std;

int main()
{
	int n;
	cin >> n;
	vector<int>moNiStack;
	vector<string>result;
	for (int i = 0; i < n; i++)
	{
		string command;
		cin >> command;
		if (command == "push")
		{
			int x;
			cin >> x;
			moNiStack.push_back(x);
		}
		else if (command == "pop")
		{
			if (moNiStack.empty())
			{
				result.push_back("error");
			}
			else
			{
				result.push_back(to_string(moNiStack[moNiStack.size() - 1]));
				moNiStack.pop_back();
			}
		}
		else if (command == "top")
		{
			if (moNiStack.empty())
			{
				result.push_back("error");
			}
			else
			{
				result.push_back(to_string(moNiStack[moNiStack.size() - 1]));
			}
		}
		else
		{
			;
		}
	}

	for (int i = 0; i < result.size(); i++)
	{
		cout << result[i] << endl;
	}
	return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务