코딩고치
[백준][자료구조]스택 본문
스택 구조는 한쪽 끝에서만 자료를 넣거나 뺄수 있는 구조이다. Last-in, First-out(LIFO)의 선형 구조로 되어 있으며 가장 마지막의 들어온 데이터가 가장 먼저 나가게 된다. 가장 마지막의 들어온 자료가 의미를 가질 때 주로 사용된다고 한다.
이 문제는 스택구조를 구현해 보는 문제이다.
#include <iostream>
#include <string>
using namespace std;
class Stack
{
public:
int data[10000];
int size;
Stack() : size(0)
{
data[10000] = NULL;
}
void push(int num)
{
data[size] = num;
size += 1;
}
bool empty()
{
if (size == 0)
return true;
else
return false;
}
int pop()
{
if (empty())
return -1;
else
{
size -= 1;
return data[size];
}
}
int top()
{
if (empty())
return -1;
else
return data[size-1];
}
};
int main(void)
{
int N;
cin >> N;
Stack sta;
while (N--)
{
string func;
cin >> func;
if (func == "push")
{
int num;
cin >> num;
sta.push(num);
}
else if (func == "empty")
cout << sta.empty() << '\n';
else if (func == "pop")
{
cout << (sta.empty() ? -1 : sta.top()) << '\n';
if (!sta.empty())
sta.pop();
}
else if (func == "top")
cout << (sta.empty() ? -1 : sta.top())<<'\n';
else if (func == "size")
cout << sta.size << '\n';
}
return 0;
}
'백준 알고리즘 기초 > 자료구조' 카테고리의 다른 글
[백준][자료구조]조세퍼스 문제 (0) | 2019.09.05 |
---|---|
[백준][자료구조]큐 (0) | 2019.09.05 |
[백준][자료구조]에디터 (0) | 2019.09.05 |
[백준][자료구조]스택 수열 (0) | 2019.09.04 |
[백준][자료구조]괄호 (0) | 2019.09.04 |
Comments