스택(10828)

NJW·2021년 8월 28일
0

코테

목록 보기
91/170

들어가는 말

스택을 구현하는 문제이다.

코드 설명

c++ 스택을 찾아보니 이미 구현이 된 헤더 파일이 있다는 걸 발변했다. 처음에는 stack 헤더 파일을 포함해서 풀었는데 런타임 에러... 그래서 일단 vector로 풀고 다음에는 stack으로 풀었다. 나중에 stack으로 풀 때는 맞더라..? pop에서 스택이 비었을 때는 -1을 출력하는 조건문만 추가해 줬는데... 흠...

코드

벡터

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

using namespace std;

int main() {
	int num;
	vector<int> v;

	cin >> num;

	for (int i = 0; i < num; i++) {
		string input;
		cin >> input;

		if (input == "push") {
			int n;
			cin >> n;
			v.push_back(n);
		}
		else if (input == "pop") {
			if (v.empty()) {
				cout << -1 << endl;
			}
			else {
				cout << v.back() << endl;
				v.pop_back();
			}
		}
		else if (input == "size") {
			cout << v.size() << endl;
		}
		else if (input == "empty") {
			if (v.empty()) {
				cout << 1 << endl;
			}
			else {
				cout << 0 << endl;
			}
		}
		else if (input == "top") {
			if (v.empty()) {
				cout << -1 << endl;
			}
			else {
				cout << v.back() << endl;
			}
		}
	}
}

스택

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

using namespace std;

int main() {
	int num;
	stack<int> v;

	cin >> num;

	for (int i = 0; i < num; i++) {
		string input;
		cin >> input;

		if (input == "push") {
			int n;
			cin >> n;
			v.push(n);
		}
		else if (input == "pop") {
			if (v.empty()) {
				cout << -1 << endl;
			}
			else {
				cout << v.top() << endl;
				v.pop();
			}
		}
		else if (input == "size") {
			cout << v.size() << endl;
		}
		else if (input == "empty") {
			if (v.empty()) {
				cout << 1 << endl;
			}
			else {
				cout << 0 << endl;
			}
		}
		else if (input == "top") {
			if (v.empty()) {
				cout << -1 << endl;
			}
			else {
				cout << v.top() << endl;
			}
		}
	}
}
profile
https://jiwonna52.tistory.com/

0개의 댓글