Programming/Baekjoon

백준 10828 c++

fishersheep 2022. 1. 19. 17:19
반응형

백준: 스택

난이도: 실버4

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

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	stack<int> s;	//스택선언
	string str;

	int n;
	cin >> n;	//명령의수

	for (int i = 0; i <= n; i++)
	{
		getline(cin, str,'\n');	//명령을 입력받음
		int temp = 0;

		if (str.find("push") != string::npos)	//문자열이 push 일경우
		{
			for (int j = 0; j < str.length(); j++)	//정수를 찾는 반복문
			{
				if (str[j] >= 48 && str[j] <= 57)	//아스키코드활용
					temp = temp * 10 + (str[j] - '0');	
			}
			s.push(temp);	//스택에 push
		}
		else if (str.find("pop") != string::npos)	//pop일 경우
		{
			if (s.empty())	//비어있으면 -1출력
				cout << -1 << '\n';
			else
			{
				cout << s.top() << '\n';	//가장위에있는 정수출력
				s.pop();	//정수삭제
			}
		}
		else if (str.find("size") != string::npos)	//size 반환
			cout << s.size() << '\n';

		else if (str.find("empty") != string::npos)	//비어있는지 확인
		{
			if (s.empty())
				cout << 1 << '\n';
			else
				cout << 0 << '\n';
		}
		else if (str.find("top") != string::npos)	//top 일 경우
		{
			if (s.empty())	//비어있으면 -1 아니면 가장 위 정수 출력
				cout << -1 << '\n';
			else
				cout << s.top() << '\n';
		}

	}

	return 0;
}
반응형

'Programming > Baekjoon' 카테고리의 다른 글

백준 10866 c++  (0) 2022.01.20
백준 10845 c++  (0) 2022.01.20
백준 11651 c++  (0) 2022.01.18
백준 11650 c++  (0) 2022.01.18
백준 11170 c++  (0) 2022.01.18