본문 바로가기

백준

[백준] 10828번 - 스택 기본

#include <iostream>

using namespace std;

int main() {	
	int cases;
	cin >> cases;

	int* stack;
	int size = 0;
	int top = -1;
	stack = new int[cases];//case 만큼의 스택 만듦
	for (int i = 0; i < cases; i++) {
		stack[i] = 0;
	}

	for (int i = 0; i < cases; i++) {
		string command;
		cin >> command;
		if (command == "push") {
			int data;
			cin >> data;
			if (++top < cases) {
				stack[top] = data;
				size++;
			}
		}
		else if (command == "pop") {
			if (size > 0) {
				cout << stack[top] << '\n';
				stack[top--] = 0;
				size--;
			}
			else
				cout << -1 << '\n';
		}
		else if (command == "size") {
			cout << size << '\n';
		}
		else if (command == "empty") {
			if (size != 0)
				cout << 0 << '\n';
			else
				cout << 1 << '\n';
		}
		else if (command == "top") {
			if (size > 0)
				cout << stack[top] << '\n';
			else
				cout << -1 << '\n';
		}		
	}
	delete[] stack;
	return 0;
}

 

스택은 가장 먼저 들어간 데이터가 가장 나중에 나온다. (Last In First Out)

위 코드에서는 스택의 용량을 동적으로 할당하기 위해 포인터를 사용하였고 정수형이므로 정수를 저장하는 스택이다.

size는 스택에 들어가 있는 정수의 개수이며 top은 스택에서 가장 위에 놓여져 있는 요소이다.

push로 데이터를 한 개씩 넣을 수 있고 pop으로 한 개씩 꺼낼 수 있다.