๐ฃ ๋ฌธ์ ์ดํด
์ ์๋ฅผ ์ ์ฅํ๋ ์คํ์ ๊ตฌํํ ๋ค์, ์ ๋ ฅ์ผ๋ก ์ฃผ์ด์ง๋ ๋ช ๋ น์ ์ฒ๋ฆฌํ๋ ํ๋ก๊ทธ๋จ์ ์์ฑํ๋ค.
๋ช ๋ น์ push, pop, top, size, empty๋ก ์ด ๋ค์ฏ ๊ฐ์ง์ด๋ค.
์คํ(Stack) ๋จ์ ๊ตฌํ ๋ฌธ์ ์ด๋ค.
๐ญ ํ์ด ๊ณผ์
C++ template์ ํ์ฉํ์ฌ Linked-List๋ก ์คํ์ ๊ตฌํํ์๋ค.
์์ฑ ์ธ์ด: C++
#include <iostream>
using namespace std;
template <typename T>
class Node {
public:
T value;
Node<T> *next;
Node<T>(): next(nullptr){}
Node<T>(T tValue, Node<T> *tNext): value(tValue), next(tNext){}
};
template <typename T>
class Stack {
public:
int size;
Node<T> *head;
Stack<T>(): size(0), head(nullptr){}
~Stack<T>() {
while (head != nullptr) {
Node<T> *temp = head->next;
delete head;
head = temp;
}
}
void Push (T value) {
head = new Node<T>(value, head);
size += 1;
}
void Pop () {
if (size != 0) {
cout << head->value << endl;
Node<T> *temp = head->next;
delete head;
head = temp;
size -= 1;
}else {
cout << "-1" << endl;
}
}
void Size () {
cout << this->size << endl;
}
void empty() {
int result = size == 0 ? 1 : 0;
cout << result << endl;
}
void top() {
if (size != 0) {
cout << head->value << endl;
}else {
cout << "-1" << endl;
}
}
};
int main() {
Stack<int> stack;
int orderCnt = 0, num = 0;
string order = "";
cin >> orderCnt;
while (orderCnt--) {
cin >> order;
if (order == "push") {
cin >> num;
stack.Push(num);
}else if (order == "pop") {
stack.Pop();
}else if (order == "size") {
stack.Size();
}else if (order == "empty") {
stack.empty();
}else if (order == "top") {
stack.top();
}else {
cout << "์ฅ ์ด์ํ ๋ช
๋ น์ด์ธ๋ฐ??" << endl;
exit(1);
}
}
}
Linked-List๋ฅผ ํ์ฉํ์ฌ Stack์ ๊ตฌํํ์๋ค.
๋ฆฌ์คํธ์ ๊ฐ ๋ ธ๋๋ ์๋ฃํ Tํ value์ ๋ค์ ๋ ธ๋๋ฅผ ๊ฐ๋ฆฌํค๋ Node ํ ํฌ์ธํฐ next๋ก ๊ตฌ์ฑ๋์ด์๋ค.
Stack ํด๋์ค์ ๊ฐ ํจ์์ ๊ธฐ๋ฅ์ ๋ค์๊ณผ ๊ฐ๋ค.
- void Push (T value): value ๊ฐ์ ์คํ์ ๋ฃ๋ ์ฐ์ฐ์ด๋ค.
- void Pop (): ์คํ์์ ๊ฐ์ฅ ์์ ์๋ ์ ์๋ฅผ ๋นผ๊ณ , ๊ทธ ์๋ฅผ ์ถ๋ ฅํ๋ค. ๋ง์ฝ ์คํ์ ๋ค์ด์๋ ์ ์๊ฐ ์๋ ๊ฒฝ์ฐ์๋ -1์ ์ถ๋ ฅํ๋ค.
- void Size (): ์คํ์ ๋ค์ด์๋ ์ ์์ ๊ฐ์๋ฅผ ์ถ๋ ฅํ๋ค.
- void empty (): ์คํ์ด ๋น์ด์์ผ๋ฉด 1, ์๋๋ฉด 0์ ์ถ๋ ฅํ๋ค.
- void top (): ์คํ์ ๊ฐ์ฅ ์์ ์๋ ์ ์๋ฅผ ์ถ๋ ฅํ๋ค. ๋ง์ฝ ์คํ์ ๋ค์ด์๋ ์ ์๊ฐ ์๋ ๊ฒฝ์ฐ์๋ -1์ ์ถ๋ ฅํ๋ค.
๐ ๋ฐฐ์ด ์
์ด๋ก ์ผ๋ก ์ดํดํ๋ ๊ฒ์ ๋ํ์ฌ ์ง์ ๊ตฌํํ๋ ์ฐ์ต์ ์ค์์ฑ์ ์์ผ ๋๋ผ๊ฒ ๋์๋ค.
๋งํฌ๋ ๋ฆฌ์คํธ๋ก ์ง์ ๊ตฌํํด๋ณด๋ฉด์ ์๋ฃ๊ตฌ์กฐ ์์ ์ ๋ฐฐ์ฐ๊ณ ๊ตฌํํ๋ ๋ด์ฉ์ด ๋ณต์ต์ด ๋์ด ์ ์ตํ ํ์ด์๋ค.
'Problem_Solving' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[BOJ] ๋ฐฑ์ค 1935 ํ์ ํ๊ธฐ์2 / ์คํ(Stack) (0) | 2020.07.27 |
---|---|
[BOJ] ๋ฐฑ์ค 1918 ํ์ ํ๊ธฐ์ / ์คํ(Stack) (0) | 2020.07.18 |
[2019 ์นด์นด์ค ๊ฐ๋ฐ์ ๊ฒจ์ธ ์ธํด์ญ] ๋ถ๋ ์ฌ์ฉ์ (0) | 2020.05.01 |
[2019 ์นด์นด์ค ๊ฐ๋ฐ์ ๊ฒจ์ธ ์ธํด์ญ] ํํ (0) | 2020.05.01 |
[2019 ์นด์นด์ค ๊ฐ๋ฐ์ ๊ฒจ์ธ ์ธํด์ญ] ํฌ๋ ์ธ ์ธํ๋ฝ๊ธฐ ๊ฒ์ (0) | 2020.05.01 |