티스토리 뷰

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");
	}
}
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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
글 보관함