/*汉诺塔递归和非递归算法实现*/ #include <iostream> using namespace std; void fun(int N,char a,char b,char c)//递归算法 { if (N==1) { cout<<a<<"-->"<<c<<endl; return; } fun(N-1,a,c,b); cout<<a<<"-->"<<c<<endl; fun(N-1,b,a,c); } void main() { fun(3,'A','B','C'); }
/*汉诺塔递归和非递归算法实现*/ #include <iostream> using namespace std; typedef struct Tower{ int height; char a,b,c; }Tower; typedef struct Node{ Tower element; Node* pNext; }Node,*LinkList; typedef struct { LinkList Top; }Stack; void InitStack(Stack& stack) { stack.Top=(LinkList)malloc(sizeof(Node)); stack.Top->pNext=NULL; } void DestroyStack(Stack& stack) { free(stack.Top); stack.Top=NULL; } void Push(Stack& stack,int height,char a,char b,char c) { LinkList temp=(LinkList)malloc(sizeof(Node)); temp->element.height=height; temp->element.a=a; temp->element.b=b; temp->element.c=c; temp->pNext=stack.Top->pNext; stack.Top->pNext=temp; } Tower Pop(Stack& stack) { LinkList temp=stack.Top->pNext; stack.Top->pNext=temp->pNext; Tower element=temp->element; free(temp); return element; } int EmptyStack(Stack stack) { if (stack.Top->pNext==NULL) { return 1; } else { return 0; } } void main() { Stack stack; InitStack(stack); Push(stack,10,'A','B','C'); while (!EmptyStack(stack)) { Tower temp=Pop(stack); if (temp.height==1) { cout<<temp.a<<"-->"<<temp.c<<endl; } else { Push(stack,temp.height-1,temp.b,temp.a,temp.c); Push(stack,1,temp.a,temp.b,temp.c); Push(stack,temp.height-1,temp.a,temp.c,temp.b); } } DestroyStack(stack); }