하노이타워를 한번 짜봤습니다.
스택도 만들어서 직접 물리적인 하노이타워라고 생각해보고 만들었는 데
더 잘 이해가 가는 소스가 될 지..
오히려 이해가 안가는 소스가 될 지 모르겠네요 ㅋㅋ
이상한 점이 있다면 문의주세요
#include<iostream>
using namespace std;
enum {A, B, C};
class stack_node{
public:
char value;
stack_node* next;
stack_node(char _value){ value = _value; next = NULL;};
};
class simple_Stack{
private:
stack_node* head;
char myname;
public:
simple_Stack(char name);
~simple_Stack();
void push(char value);
char pop();
bool isEmpty();
void show();
void showReverse(stack_node* show_node);
};
simple_Stack::simple_Stack(char name){
head = NULL;
myname = name;
}
simple_Stack::~simple_Stack(){
while(!isEmpty())
pop();
}
void simple_Stack::push(char value){
stack_node* tmp = new stack_node(value);
tmp->next = head;
head = tmp;
}
char simple_Stack::pop(){
if(isEmpty())
return '0';
stack_node* tmp = head;
char ret = tmp->value;
head = tmp->next;
delete tmp;
return ret;
}
bool simple_Stack::isEmpty(){
return (!head);
}
void simple_Stack::show(){
cout << myname << " : ";
showReverse(head);
cout << endl;
}
void simple_Stack::showReverse(stack_node* show_node){
if(show_node != NULL)
{
showReverse(show_node->next);
cout << show_node->value << " ";
}
}
//////////////////////////////////////////////////////////
class hanoi{
private:
simple_Stack* top[3];
int numofdisk;
int step;
public:
hanoi(int _num);
~hanoi();
void move(int from, int to, int num);
int else_thing(int thing_1, int thing_2);
char enum_value(int abc);
void show();
};
hanoi::hanoi(int _num){
numofdisk = _num;
top[A] = new simple_Stack('A');
top[B] = new simple_Stack('B');
top[C] = new simple_Stack('C');
if(_num > 26)
_num = 26;
for(int i = 0; i < _num; i ++)
top[A]->push('A'+i);
step = 0;
}
hanoi::~hanoi(){
delete top[A];
delete top[B];
delete top[C];
}
void hanoi::move(int from, int to, int num){
if(num == 1)
{
top[to]->push(top[from]->pop());
cout << endl << " step [" << step++ << "] ";
cout << enum_value(from) << "->" << enum_value(to) << endl;
show();
}
else
{
move(from, else_thing(from, to), num-1);
move(from, to, 1);
move(else_thing(from, to), to, num-1);
}
}
void hanoi::show(){
top[A]->show();
top[B]->show();
top[C]->show();
}
int hanoi::else_thing(int thing_1, int thing_2){
int sum = thing_1 + thing_2;
if(sum == 1)
return C;
else if(sum == 2)
return B;
return A;
}
char hanoi::enum_value(int abc){
if(abc == 0)
return 'A';
else if(abc == 1)
return 'B';
return 'C';
}
//////////////////////////////////////////
int main()
{
hanoi h(5);
h.show();
h.move(A, C, 5);
}