티스토리 뷰
Stack STL 방식 하나와 배열로 스택을 구현한 방식 두가지로 문제를 풀었습니다.
Stack STL 방식
더보기
#include<iostream>
#include<stack>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(nullptr);
int n;
stack<int> Stack;
cin >> n;
for(int i = 0;i<n;i++) {
string s;
cin >> s;
if (s == "push") {
int input;
cin >> input;
Stack.push(input);
}
else if (s == "top") {
if (Stack.empty())
cout << -1 << "\n";
else
cout << Stack.top() << "\n";
}
else if (s == "size") {
cout << Stack.size() << "\n";
}
else if (s == "empty") {
if(Stack.empty())
cout << 1 << "\n";
else
cout << 0 << "\n";
}
else if (s == "pop") {
if (!Stack.empty()) {
cout << Stack.top() << "\n";
Stack.pop();
}
else {
cout << -1 << "\n";
}
}
}
}
배열 Stack 형식
더보기
#include<stdio.h>
#include<string.h>
int number[10000];
void push(int a);
void pop();
void size();
void empty();
void top();
int t = 0;
int main() {
int a, i, count;
char point[5];
scanf("%d", &count);
for (i = 0; i < count; i++) {
scanf("%s", point);
if (strcmp(point,"push")==0) {
scanf("%d", &a);
push(a);
}
else if (strcmp(point, "pop")==0) {
pop();
}
else if (strcmp(point, "size")==0) {
size();
}
else if (strcmp(point, "empty")==0) {
empty();
}
else if (strcmp(point, "top")==0) {
top();
}
else {
printf("다시입력해주세요.\n");
}
}
}
void push(int a) {
number[++t] = a;
}
void pop() {
if(t != 0){
printf("%d\n", number[t]);
t -= 1;
}else{
printf("-1\n");
}
}
void size() {
printf("%d\n", t);
}
void empty() {
if (t != 0) {
printf("0\n");
}
else {
printf("1\n");
}
}void top() {
if (t != 0) {
printf("%d\n", number[t]);
}
else {
printf("-1\n");
}
}
'자료구조 및 알고리즘 > 문제풀이' 카테고리의 다른 글
백준 C++ 4949번) 균형잡힌 세상 (0) | 2022.07.17 |
---|---|
백준 C++ 10845번) 큐 (0) | 2022.07.17 |
백준 C++ 1406번) 에디터 (0) | 2022.07.16 |
백준 C++ 1904번) 01타일 (0) | 2022.07.16 |
백준 C++ 9148번 ) 신나는 함수 실행 (0) | 2022.07.16 |
댓글