๊ณต๋ถ€/์ฝ”๋”ฉ

[c++] ๋ฐฑ์ค€ 10828 ์Šคํƒ

sourceoftax 2025. 8. 2. 22:14

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

using namespace std;


int main() {
	stack<int> st;
	string s;
	int num(0), inputNum(0);

	cin >> num;
	for (int i = 0; i < num; i++) {
	cin >> s;
	if (s == "push") {
		cin >> inputNum;
		st.push(inputNum);
	}

	else if (s == "pop") {

		if (!st.empty()) {
			cout << st.top() << '\n';
			st.pop();
		}
		else cout << -1 << '\n';
	}

	else if (s == "size") cout << st.size() << '\n';

	else if (s == "empty") {
		cout << (st.empty() ? 1 : 0) << '\n';
	}

	else if (s == "top") {
		if (!st.empty()) {
			cout << st.top() << '\n';
		}
		else cout << -1 << '\n';
	}
}
	return 0;
}

์Šคํƒ์€ ์ž์ฃผ ์‚ฌ์šฉ๋˜๋Š” ์ž๋ฃŒ๊ตฌ์กฐ ์ค‘ ํ•˜๋‚˜์ด๋‹ค. ํ›„์ž…์„ ์ถœ ๋ฐฉ์‹/LIFO ๋ฐฉ์‹์œผ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ๊ด€๋ฆฌํ•˜๋Š”๋ฐ, ์†”์งํžˆ ๋‚˜๋Š” ํŽธ์˜์  ์•Œ๋ฐ”๋„ ํ–ˆ์ง€๋งŒ ์ด ๋‹จ์–ด๊ฐ€ ๋„ˆ๋ฌด ์–ด์ƒ‰ํ•จ... ๊ทธ๋ƒฅ ์ œ์ผ ๋‚˜์ค‘์— ๋“ค์–ด์˜จ๊ฒŒ ์ฒ˜์Œ์œผ๋กœ ๋‚˜๊ฐ€๋Š” ๋ฐฉ์‹์ด๋‹ค. ํ”„๋ง๊ธ€์Šค ๊ณผ์žํ†ต๊ฐ™์€ ๋А๋‚Œ? ๋งจ ์œ„์— ์žˆ๋Š” ๊ฒƒ๋ถ€ํ„ฐ ๊ฐ€์ ธ๊ฐ„๋‹ค.

์ง์ ‘๊ทธ๋ ธ์œผ๋‹ˆ์•…ํ”Œ์€ใ„ดใ„ด

์•ฝ๊ฐ„ ์ด๋Ÿฐ ๋А๋‚Œ์ด๋‹ค

C++์—์„œ๋Š” include <stack>์„ ํ†ตํ•ด ์†์‰ฝ๊ฒŒ ๋ฏธ๋ฆฌ ๊ตฌํ˜„๋œ ํ•จ์ˆ˜๋“ค์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.