하나의 배열을 이용해서, 두개의 스택을 구현하는 내용이다.
/*
3.a) 하나의 배열에 stack 2개를 어떻게 구현할 것인가?
일단 max size가 정해져 있다는 점을 이용해, 1000보다 작은 건 순서대로,
큰 것은 역순으로 삽입한다.
*/
/*
3.b) 클래스 정의
*/
const int MAX_ITEMS = 200;
#include <iostream>
#include <ctime>
#include <cstdlib>
class Double_stack {
private:
int Items[MAX_ITEMS];
int less_top;
int greater_top;
public:
Double_stack() {
less_top = -1;
greater_top = 200;
}
void Push(int item);
void Print();
void Pop();
bool isFull();
bool isEmpty_less();
bool isEmpty_greater();
};
/*
3.c)PUSH 클래스 구현
*/
void Double_stack::Push(int item) {
if (this->isFull() == true) {
std::cout << "배열이 꽉찼어염" << std::endl;
}
else {
if (item <= 1000) {
this->less_top++;
Items[less_top] = item;
}
else {
this->greater_top--;
Items[greater_top] = item;
}
}
}
bool Double_stack::isFull() {
if (this->less_top == this->greater_top) {
return true;
}
else {
return false;
}
}
// 3.d) Print 함수 구현
bool Double_stack::isEmpty_less() {
if (this->less_top == -1) {
return true;
}
else {
return false;
}
}
bool Double_stack::isEmpty_greater() {
if (this->greater_top == 200) {
return true;
}
else {
return false;
}
}
void Double_stack::Pop() {
if (this->isEmpty_less() == false) {
less_top--;
}
else if(this->isEmpty_greater() == false){
greater_top++;
}
else {
std::cout << "배열이 비어있습니다" << std::endl;
}
}
void Double_stack::Print() {
int i = 0;
std::cout << "작은 스택들" << std::endl;
while (i < this->less_top) {
auto result = this->Items[i];
std::cout << i << " 번째 들어있는 값: " << result << std::endl;
i++;
}
if (this->Items[i] <= 1000) {
auto result = this->Items[i];
std::cout << i << " 번째 들어있는 값: " << result << std::endl;
}
i = 199;
std::cout << "큰 스택들" << std::endl;
while (i > this->greater_top) {
auto result = this->Items[i];
std::cout << i << " 번째 들어있는 값: " << result << std::endl;
i--;
}
if (this->Items[i] > 1000) {
auto result = this->Items[i];
std::cout << i << " 번째 들어있는 값: " << result << std::endl;
}
}
int main() {
Double_stack stack;
srand(10);
int i = 0;
while (i < 206) {
stack.Push(rand() % 10000);
i++;
}
stack.Print();
}