IT 프로그래밍/백준

[C++] 백준 10828 스택

기술1 2024. 11. 3. 16:23

정답코드

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


int main()
{
	stack<int> s;
	int N;
	string command;
	int num;
	int result = 0;

	cin >> N;

	for(int i=0; i<N; i++)
	{
		cin >> command;

		if(command == "push")
		{
			cin >> num;
			s.push(num);
		}
		else if(command == "pop")
		{
			if (s.size() == 0)
			{
				result = -1;
				cout << result << endl;
			}
			else
			{
				result = s.top();
				cout << result << endl;
				s.pop();
			}
		}
		else if(command == "size")
		{
			result = s.size();
			cout << result << endl;
		}
		else if(command == "empty")
		{
			if (s.empty())
				cout << 1 << endl;
			else
				cout << 0 << endl;
		}
		else if(command == "top")
		{
			if(s.size() == 0)
			{
				cout << -1 << endl;
			}
			else
				cout << s.top() << endl;
		}
		
	}

	return 0;
}

c++은 스택을 지원하기 때문에 라이브러리에 스택을 넣어주고 해주시면 됩니다.

 

coimmand로 각각 입력받을 것을 if문을 걸어준 뒤 각 동작에 해당하는 것을 만들어주면 됩니다. push의 경우 그냥 push를 넣어주면 되고 pop의 경우 size가 0이면 -1, 그 이외에는 출력 후 pop을 해야하기 때문에 top 이후 pop을 해줍니다.

 

size는 s.size()로 해주고 empty의 경우도 if(s.empty()) 일 경우 출력이 되도록 해줍니다. 아니면 s.size() == 0 일때 해줘도 상관 없습니다. 

 

마지막 top일때 스택에 값이 없으면 -1, 아니면 top()을 해주면 됩니다. 

 

스택의 개념을 알아가는 문제이기 때문에 문제를 읽고 그대로 하면 되는 난이도가 쉬운 문제입니다. 

'IT 프로그래밍 > 백준' 카테고리의 다른 글

[c++] 1874번 스택 수열  (0) 2024.11.05
[C++] 백준 10773 제로  (0) 2024.11.03
[C++] 백준 5086번 배수와 약수  (0) 2024.11.03
[C++] 백준 9012번 괄호  (0) 2024.11.03
[백준] 1032 명령 프롬프트 c++  (0) 2024.10.08