반응형
출처: http://www.jungol.co.kr/bbs/board.php?bo_table=pbank&wr_id=382&sca=2070
Approach
Stack 자료구조 이용
[C++] [STL] Stack
Stack 기본 연산 - LIFO 구조 (Last In First Out) - push(element) : 스택 (뒤쪽에) 원소 추가 - pop() : 스택에 (뒤쪽에) 있는 원소 삭제 (반환 x) - top() : 스택에서 끝에 있는 원소 반환 - empty() : 스택이..
zoosso.tistory.com
[스택] Stack 이란?
Stack 이란? 스택 (Stack) 특징을 가장 잘 나타내는 표현은 후입선출(Last In First Out, LIFO) 이다. ▶ 스택(Stack)은 삽입(push)과 삭제(pop)이 한쪽 끝에서만 일어나는 구조 가장 상단에 위치한 원소를 가리.
zoosso.tistory.com
방법 1
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
struct Stack {
int num;
Stack* next;
Stack(int _num, Stack* _next) {
num = _num, next = _next;
}
} *head;
int cnt;
void push(int num) {
head = new Stack(num, head);
cnt++;
}
void pop() {
if (cnt == 0) {
printf("empty\n");
return;
}
printf("%d\n", head->num);
Stack* newnode = head;
head = head -> next;
delete(newnode);
cnt--;
}
int main() {
// freopen("input.txt", "r", stdin);
int N, num;
char cmd;
scanf("%d", &N);
while (N--) {
scanf(" %c", &cmd);
if(cmd == 'i') {
scanf("%d", &num);
push(num);
}
else if (cmd == 'o') {
pop();
}
else {
printf("%d\n", cnt);
}
}
}
방법 2
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
struct Stack {
int num;
Stack* next;
Stack* alloc(int _num, Stack* _next) {
num = _num, next = _next;
return this;
}
} *head, buf[100];
int cnt, bufcnt;
void push(int num) {
head = buf[bufcnt++].alloc(num, head);
cnt++;
}
void pop() {
if (cnt == 0) {
printf("empty\n");
return;
}
printf("%d\n", head->num);
head = head->next;
cnt--;
}
int main() {
// freopen("input.txt", "r", stdin);
int N, num;
char cmd;
scanf("%d", &N);
while (N--) {
scanf(" %c", &cmd);
if(cmd == 'i') {
scanf("%d", &num);
push(num);
}
else if (cmd == 'o') {
pop();
}
else {
printf("%d\n", cnt);
}
}
return 0;
}
반응형
'PS 문제 풀이 > Jungol' 카테고리의 다른 글
[Jungol] 정올 3690 stack api (0) | 2021.03.18 |
---|---|
[Jungol] 정올 3701 queue api (0) | 2021.03.18 |
[Jungol] 정올 3293 비트연산 1 (0) | 2021.03.18 |
[Jungol] 정올 3101 요세푸스 문제 1 (0) | 2021.03.18 |
[Jungol] 정올 1337 달팽이 삼각형 (0) | 2021.03.17 |
댓글