코딩고치
[백준][자료구조]덱 본문
이 문제는 자료구조 덱을 구현하는 문제이다. 이 전에 스택과 큐를 구현을 해보았다. 스택의 경우 한쪽 끝에서만 데이터를 입출력 할 수 있는 자료구조이고 큐의 경우에는 한쪽 끝에서 데이터를 입력하고 다른쪽 끝에서 데이터를 출력하는 자료구조이다. 하지만 덱은 양쪽끝에서 데이터 입출력이 모두 가능하다.
#include <iostream>
#include <string>
using namespace std;
class Deque
{
private:
int arr[100000];
int begin;
int end;
public:
Deque() : begin(0), end(0)
{
arr[100000] = 0;
}
void push_front(int num) // 데이터를 뒤로 한칸씩 미루고
{ // front에 입력을 받음
for (int i = end; i > begin; i--)
arr[i] = arr[i-1];
end++;
arr[begin] = num;
}
void push_back(int num)
{
arr[end] = num;
end++;
}
int pop_front()
{
if (begin == end)
return -1;
else
return arr[begin++];
}
int pop_back()
{
if (begin == end)
return -1;
else
return arr[--end];
}
int size()
{
return end-begin;
}
int empty()
{
if (begin==end)
return 1;
else
return 0;
}
int front()
{
if (begin==end)
return -1;
else
return arr[begin];
}
int back()
{
if (begin==end)
return -1;
else
return arr[end - 1];
}
};
int main(void)
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int x;
Deque dq;
cin >> x;
while (x--)
{
string cmd;
cin >> cmd;
if (cmd == "push_front")
{
int fnum;
cin >> fnum;
dq.push_front(fnum);
}
else if (cmd == "push_back")
{
int bnum;
cin >> bnum;
dq.push_back(bnum);
}
else if (cmd == "pop_front")
{
cout << dq.pop_front() << '\n';
}
else if (cmd == "pop_back")
{
cout << dq.pop_back() << '\n';
}
else if (cmd == "size")
{
cout << dq.size() << '\n';
}
else if (cmd == "empty")
{
cout << dq.empty() << '\n';
}
else if (cmd == "front")
{
cout << dq.front() << '\n';
}
else if (cmd == "back")
{
cout << dq.back() << '\n';
}
}
return 0;
}
'백준 알고리즘 기초 > 자료구조' 카테고리의 다른 글
[백준][자료구조]쇠막대기 (0) | 2019.09.06 |
---|---|
[백준][자료구조]단어 뒤집기 (0) | 2019.09.06 |
[백준][자료구조]조세퍼스 문제 (0) | 2019.09.05 |
[백준][자료구조]큐 (0) | 2019.09.05 |
[백준][자료구조]에디터 (0) | 2019.09.05 |
Comments