delpho

[C++, 10828] 스택 본문

알고리즘/구현

[C++, 10828] 스택

delpho 2021. 7. 15. 15:45

본격적으로 자료구조 공부를 시작했다.

 

스택 문제를 C++로 하나하나 구현해보았다.

 

#include <iostream>
#include <cstring>
using namespace std;

int N;
int stack[10001];
int tail = -1;

void push(int commandNum) {
	stack[++tail] = commandNum;
}

void pop() {
	if (tail != -1) {
		cout << stack[tail] << '\n';
		stack[tail] = 0;
		tail--;
	}
	else cout << -1 <<'\n';
}

void empty() {
	if (tail != -1) cout << 0 << '\n';
	else cout << 1 << '\n';
}

void size() {
	cout << tail+1 << '\n';
}

void top() {
	if (tail != -1) {
		cout << stack[tail]<<'\n';
	}
	else cout << -1 << '\n';

}

int main(){
	int commandNum;

	cin >> N;
	char command[6];


	for (int i = 0; i < N; i++) {
		cin >> command;
		

		if (!strcmp(command, "push")) {
			cin>>commandNum;
			push(commandNum);
		}
		else if (!strcmp(command, "pop")) {
			pop();
		}
		else if (!strcmp(command, "empty")) {
			empty();
		}
		else if (!strcmp(command, "size")) {
			size();
		}
		else {
			top();
		}
	}
}

 

cout 하는 곳에서 줄바꿈을 하지않아서 계속 틀렸다고 떴었다.

이 부분을 신경쓰도록 해봐야겠다.

 

링크드리스트와 내장 함수를 이용해서 푸는 풀이도 공부해서 추가해봐야겠다.