[BOJ] 10828번 스택

뚜비·2022년 6월 23일
0

BOJ

목록 보기
11/11

스택 << 문제 클릭!



✅문제 설명

스택을 구현하고 다음과 같은 명령을 처리한다.


  • 입력
    : 첫째 줄에는 명령의 수 N (1 <= N <= 10,000)
    : 둘째 줄 ~ N개의 줄 명령이 하나씩 주어짐
    : 주어진 정수는 1보다 크거나 같고 100,000보다 작거나 같다

  • 출력
    : 출력해야 하는 명령이 주어질 때마다, 한 줄에 하나씩 출력!


❗핵심원리

  • 스택
    Last in First Out(LIFO)

마지막 원소의 인덱스를 저장하는 변수를 따로 만들면 된다!



💻코드

1차

#include <iostream>

using namespace std;

void push(int x);
int pop();
int size();
int empty();
int top();

// 전역변수 
int idx = 0; // 현재 원소 개수 
int arr[10000];

int main(void) {
	ios::sync_with_stdio(0);
	cin.tie(0);

	int inputOrder = 0;
	string inputString = "";
	cin >> inputOrder;

	for (int i = 0; i < inputOrder; i++) {
		cin >> inputString;
		if (inputString == "push") {
			int inputX = 0;
			cin >> inputX;
			push(inputX);
		}
		else if (inputString == "pop") {
			cout << pop() << "\n";
		}
		else if (inputString == "size") {
			cout << size() << "\n";
		}
		else if (inputString == "empty"){
			cout << empty() << "\n";
		}
		else {
			// top
			cout << top() << "\n";
		}
	}
}

void push(int x) {
	arr[idx] = x;
	idx++;
}

int pop() {
	if (idx == 0) {
		return -1;
	}
	else {
		int top = arr[idx - 1];
		idx--;
		return top;
	}
	
}

int size() {
	return idx;
}

int empty() {
	if (idx == 0) return 1;
	else return 0;
}

int top() {
	if (idx == 0) return -1;
	else {
		return arr[idx - 1];
	}
}

profile
SW Engineer 꿈나무 / 자의식이 있는 컴퓨터

0개의 댓글

Powered by GraphCDN, the GraphQL CDN