티스토리 뷰
개요:스택은 한쪽 끝에서만 자료를 넣고 뺄 수 있는 LIFO(Last In First Out) 형식의 자료구조이다.
연산:
push(x): 스택 가장 위 에 x를 추가한다.
pop(): 스택 가장 위에 있는 항목을 제거한다.
top(): 가장 위에 있는 항목을 반환한다.
size(): 스택의 크기를 반환한다.
구현: 배열이나 링크드 리스트를 이용해 구현할 수 있는데, 나는 배열로 구현했다.
#include <iostream>
#include <assert.h>
#include <string>
//https://www.acmicpc.net/problem/10828 문제 풀이
using namespace std;
template <typename T>
class stack
{
T arr[1000100];
const int maxsiz = 1000000;
int siz = 0;
public:
int push(T x)
{
if (siz == maxsiz)
return -1;
arr[siz++] = x;
return 0;
}
int pop()
{
if (siz == 0)
return -1;
siz--;
return 0;
}
int size()
{
return siz;
}
T top()
{
assert(siz);
return arr[siz - 1];
}
};
stack<int>x;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int T;
cin >> T;
while (T--)
{
string s;
cin >> s;
if (s == "push")
{
int n;
cin >> n;
x.push(n);
}
else if (s == "pop")
{
if (x.size())
{
cout << x.top() << '\n';
x.pop();
}
else
{
cout << -1 << '\n';
}
}
else if (s == "top")
{
if (x.size())
{
cout << x.top() << '\n';
}
else
{
cout << -1 << '\n';
}
}
else if (s == "size")
{
cout <<x.size()<< '\n';
}
else
{
cout << !x.size() << '\n';
}
}
}
'algorithm' 카테고리의 다른 글
APIO 2013 interference (0) | 2021.09.28 |
---|---|
스택 문제풀이 (0) | 2021.09.09 |