#include <iostream>
using namespace std;
struct StackNode{
int value;
StackNode * next;
StackNode(int v)
{
value = v;
next = NULL;
}
};
class Stack
{
private:
StackNode * head;
public:
Stack()
{
head = NULL;
}
~Stack()
{
while (head != NULL)
{
StackNode * node = head;
head = head->next;
delete node;
}
head = NULL;
}
void push(int value)
{
StackNode * node = new StackNode(value);
if (head == NULL)
head = node;
else
{
node->next = head;
head = node;
}
}
int pop()
{
if (head == NULL)
{
cout<<"error"<<endl;
return -1;
}
StackNode * node = head;
int value = node->value;
head = head->next;
delete node;
return value;
}
int top()
{
if (head != NULL)
return head->value;
else
{
cout<<"NULL"<<endl;
return -1;
}
}
bool isEmpty()
{
return head == NULL;
}
};
class Hanoi
{
private:
Stack stick[3];
int num;
public:
Hanoi(int n)
{
num = n;
for (int i = n; i > 0; i--)
{
stick[0].push(i);
}
}
void move(int x, int y, int z, int n)
{
if (n == 1)
{
int value = stick[x].pop();
stick[z].push(value);
cout<<"move from "<<x<<" to "<<z<<endl;
}
else if (n == 2)
{
int value = stick[x].pop();
stick[y].push(value);
cout<<"move from "<<x<<" to "<<y<<endl;
value = stick[x].pop();
stick[z].push(value);
cout<<"move from "<<x<<" to "<<z<<endl;
value = stick[y].pop();
stick[z].push(value);
cout<<"move from "<<y<<" to "<<z<<endl;
}
else
{
move(x, z, y, n - 1);
move(x, y, z, 1);
move(y, z, x, n - 1);
}
}
};
int main()
{
Hanoi h(3);
h.move(0,1,2,3);
return 0;
}
crack the code interview 3.4
最新推荐文章于 2018-12-16 22:24:21 发布