문제 이해
코드
cpp 파일
// 전처리 단계(컴파일되기 이전 단계에서 실행됨)
#include <iostream>
#include "baekjoon.h";
using namespace std;
const int MX = 100005;
int dat[MX*2+1];
int head = MX;
int tail = MX;
// 구현부
void push_front(int val) {
dat[head--] = val;
}
void push_back(int val) {
dat[++tail] = val;
}
// C++도 C의 절차지향적 특성을 가지고 있기 때문에
// 순차적으로 코드를 빌드하는 과정에서 없는 함수를 호출하려고 하면 문제가 생김
// 그래서 선언부를 먼저 정의하고 구현부는 순서 상관없이 두어도 문제없이 실행됨
int pop_front() {
if (empty()) {
return -1;
}
else {
return dat[++head];
}
}
int pop_back() {
if (empty()) {
return -1;
}
else {
return dat[tail--];
}
}
int front() {
if (empty()) {
return -1;
}
else {
return dat[head + 1];
}
}
int back() {
if (empty()) {
return -1;
}
else {
return dat[tail];
}
}
int empty() {
if (tail - head == 0) return 1;
else return 0;
}
int size() {
return tail - head;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int commandNum;
cin >> commandNum;
for (int i = 0; i < commandNum; i++) {
string command;
cin >> command;
if (command == "push_front") {
int value;
cin >> value;
push_front(value);
} else if (command == "push_back") {
int value;
cin >> value;
push_back(value);
} else if (command == "pop_front") {
cout << pop_front() << "\n";
} else if (command == "pop_back") {
cout << pop_back() << "\n";
} else if (command == "size") {
cout << size() << "\n";
} else if (command == "empty") {
cout << empty() << "\n";
} else if (command == "front") {
cout << front() << "\n";
} else if (command == "back") {
cout << back() << "\n";
}
}
return 0;
}
header 파일
/*
header 파일에 선언부를 넣는게 일반적이지만 구현도 할 수 있음
header 파일은 최대한 간단하게 선언만 하는게 좋음
*/
// #pragma once
// cpp에서 코드가 중복되는 header 파일을 여러개 포함시키는 경우 코드의 충돌이 일어나지 않게끔 함
#pragma once
int empty();
'알고리즘&자료구조' 카테고리의 다른 글
스택의 활용(수식의 괄호 쌍) (0) | 2024.02.06 |
---|---|
구간 합 (2) | 2024.01.09 |
알고리즘 코테 준비 자료구조(배열, 리스트, 벡터) (3) | 2024.01.07 |
최대공약수 활용문제 (0) | 2021.06.08 |
백준 - 2178(DFS,BFS) (0) | 2021.02.01 |