티스토리 뷰
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 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 인제대학교
- STL
- c++
- 워셜알고리즘
- 정보보안
- 학교
- Select모델
- 더블버퍼링
- Dreamhack
- 시스템보안
- 자료구조
- 링크드 리스트
- BFS
- 보안
- queue
- 스레드풀
- 지뢰찾기
- 컨퍼런스
- 드림핵
- 야경
- 고양이
- 멀티쓰레드
- 알고리즘
- 개발
- 백준
- 레지스터
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
글 보관함