본문 바로가기

algorithm/BOJ

백준 10828_스택(C++)

 

www.acmicpc.net/problem/10828

 

10828번: 스택

첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지 �

www.acmicpc.net

[문제 풀이]

STL을 이용한 것과 직접 구현한 것 두 가지로 문제를 풀어보았습니다.

 

이 문제는 단순히 스택을 구현하는 것이므로 설명은 생략하겠습니다.

코드는 STL을 이용한 코드와 직접 구현한 코드 두 가지를 적어 놓은 것입니다.

[STL 코드]

#include<iostream>
#include<stack>
#include<string>

using namespace std;

int N;

stack<int> stac;

int main() {

	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	cin >> N;

	string exec;

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

		if (exec == "push") {    //push
			int temp;
			cin >> temp;
			stac.push(temp);
		}
		else if (exec == "pop") {    //pop
			if (stac.empty())
				cout << -1 << endl;
			else {
				cout << stac.top() << endl;
				stac.pop();
			}
		}
		else if (exec == "size") {    //size
			cout << stac.size() << endl;
		}
		else if (exec == "empty") {    //empty
			if (stac.empty())
				cout << 1 << endl;
			else
				cout << 0 << endl;
		}
		else if (exec == "top") {     //top
			if (stac.empty())
				cout << -1 << endl;
			else
				cout << stac.top() << endl;
		}
	}

	return 0;
}

[직접 구현 코드]

#include<iostream>
#include<string>

using namespace std;

int arr[10000] = { 0, };

int main() {

	ios::sync_with_stdio(false);
	cin.tie(null);

	int n; cin >> n;

	int idx = -1;

	for (int i = 0; i < n; i++) {
		string str;

		cin >> str;

		if (str == "push") {
			int x; cin >> x;
			idx++;
			arr[idx] = x;
		}
		else if (str == "pop") {

			if (idx == -1)
				cout << "-1" << endl;
			else {
				cout << arr[idx] << endl;
				arr[idx] = 0;
				idx--;
			}
		}
		else if (str == "size") {
			if (idx == -1)
				cout << 0 << endl;
			else
				cout << idx + 1 << endl;
		}
		else if (str == "empty") {
			if (idx == -1)
				cout << 1 << endl;
			else
				cout << 0 << endl;
		}
		else if (str == "top") {
			if (idx == -1)
				cout << -1 << endl;
			else
				cout << arr[idx] << endl;
		}

	}


	return 0;
}

 

 

'algorithm > BOJ' 카테고리의 다른 글

백준 11279_최대 힙(C++)  (0) 2020.10.18
백준 10845_큐(C++)  (0) 2020.10.17
백준 7453_합이 0인 네 정수(C++)  (0) 2020.10.15
백준 2143_두 배열의 합(C++)  (0) 2020.10.10
백준 1806_부분합(C++)  (0) 2020.10.09