自己写了一个汉诺塔问题的小程序,定义了一个堆栈类,然后用递归实现。主要想练下手,深入理解链栈、递归这些问题。直接上代码,写的不好的地方请指导。
#include <iostream>
using namespace std;
typedef char ElemType;
//定义链表结构
typedef struct LinkNode{
LinkNode* next;
ElemType data;
}LinkNode,*Linklist;
//定义链栈类
class Stack{
public:
Linklist top;
int stack_size;
Stack():stack_size(0),top(NULL){};
public:
void PushStack(ElemType ele);
ElemType PopStack();
void PrintStack();
};
//推入元素
void Stack::PushStack(ElemType ele)
{
Linklist ss=(Linklist)malloc(sizeof(LinkNode));
ss->data=ele;
ss->next=top;
top=ss;
stack_size++;
}
//推出元素
ElemType Stack::PopStack()
{
ElemType val;
Linklist p;
if (top==NULL)
{
cout<<"STACK IS EMPTY!"<<endl;
return 0;
}
p=top;
val=p->data;
top=top->next;
free(p);
stack_size--;
return val;
}
//打印链栈里所有的元素(遍历实现)
void Stack::PrintStack()
{
if (stack_size!=0)
{
Linklist p=top;
while(p)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl<<endl;
}
else
cout<<"empty!"<<endl<<endl;
}
//移动单个圆盘操作
void Move(Stack &Src,Stack &Dest)
{
ElemType ele;
ele=Src.PopStack();
Dest.PushStack(ele);
}
//汉诺操作,将N个圆盘从Src移动至Dest,以Trans为中转
void Hanoi(int N,Stack &Src,Stack &Trans,Stack &Dest)
{
if (N==1)//递归至N=1时执行移动单个圆盘操作
{
Move(Src,Dest);
return;
}
else
{
//先将N-1个圆盘移动从Src移动至Trans,以Dest为中转
Hanoi(N-1,Src,Dest,Trans);
//再将第N个圆盘移动从Src移动至Dest
Move(Src,Dest);
//最后将N-1个圆盘从Trans移动至Dest,操作完成
Hanoi(N-1,Trans,Src,Dest);
return;
}
}
int main()
{
Stack X,Y,Z;
X.PushStack('a');
X.PushStack('b');
X.PushStack('c');
X.PushStack('d');
X.PushStack('e');
X.PushStack('f');
int N=X.stack_size;
cout<<"Hanoi之前:"<<endl;
cout<<"elements of stack X is:"<<endl;
X.PrintStack();
cout<<"elements of stack Y is:"<<endl;
Y.PrintStack();
cout<<"elements of stack Z is:"<<endl;
Z.PrintStack();
Hanoi(N,X,Y,Z);
cout<<"Hanoi之后:"<<endl;
cout<<"elements of stack X is:"<<endl;
X.PrintStack();
cout<<"elements of stack Y is:"<<endl;
Y.PrintStack();
cout<<"elements of stack Z is:"<<endl;
Z.PrintStack();
return 0;
}