백준 10828 스택 C++

황상진·2022년 6월 1일
0

Algorithm

목록 보기
2/8
post-thumbnail

백준 10828 스택

https://www.acmicpc.net/problem/10828

문제 요약

  1. 자료 구조 스택을 구현하는 문제
  2. push - 스택에 정수를 넣어준다.
  3. pop - 스택 가장 위에 수를 빼주고, 출력하고, 스택이 비어있으면 -1을 출력한다.
  4. size - 스택에 들어있는 정수의 개수를 출력한다.
  5. empty - 스택이 비어있으면 1, 아니면 0을 출력한다.
  6. top - 스택 가장 위에 정수를 출력해주고, 스택이 비어있으면 -1을 출력한다.

풀이

  1. 가장 기본적으로 스택 자료구조에 대한 이해가 필요하다.
  2. 스택은 LIFO(Last In First Out) 의 구조를 가진 자료구조이다.
  3. C++ STL Stack 라이브러리를 이용하여 구현하다.

C++ Stack 라이브러리

Stack

후입 선출 (LIFO)의 자료구조 Stack의 STL
<stack> 헤어파일 추가

#include <stack>
stack<int> st;

st.push(n);
st에 n을 삽입

st.pop();
st 마지막에 들어간 원소 삭제 (return 없음)

st.top();
st 마지막에 들어간 원소 return

st.empty();
st가 비어있는지 true, false return

st.size();
st에 들어있는 원소 수 return

st.swap(st1)
st1의 원소를 st와 전환

clear하는 법 2가지
  1. while(!st.empty()) st.pop();
  2. st = stack<int>();

코드

stack<int> st;
void push() {
	int t;
	cin >> t;

	st.push(t);
	return;
}
int pop() {
	if (st.empty()) {
		return -1;
	}
	else {
		int top = st.top();
		st.pop();
		return top;
	}
}
int size() {
	return st.size();
}
int empty() {
	if (st.empty()) {
		return 1;
	}
	else {
		return 0;
	}
}
int top() {
	if (st.empty()) {
		return -1;
	}
	else {
		int top = st.top();
		return top;
	}
}
int main() {
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);	
	
	string commandExample[5] = {"push", "pop", "size", "empty", "top"};
	int N;
	cin >> N;

	string com;
	while (N--) {
		cin >> com;

		for (int i = 0; i < 5; i++) {
			if (com == commandExample[i]) {
				if (i == 0) {
					push();
				}
				else if (i == 1) {
					cout << pop() << '\n';
				}
				else if (i == 2) {
					cout << size() << '\n';
				}
				else if (i == 3) {
					cout << empty() << '\n';
				}
				else if (i == 4) {
					cout << top() << '\n';
				}
				break;
			}
		}
	}


	return 0;
}

profile
Web FrontEnd Developer

0개의 댓글