程式本身呼叫自己本身,使用堆疊方法。
河內塔為常見例子。
河內塔計算程式
#include<stdio.h>
void hanoi ( int , int , int , int )
char tower [ ] [4] = { "1st" , "2nd" , "3rd" };
void main ( void )
{
int i;
printf( "How many plate (s) to move?" );
scanf( "%d" , &i );
hanoi( i , 0 , 1 , 2 );
}
void hanoi ( int i , int begin , int mid , int dest )
{
if (i==1)
printf ( "Move plate %d from %s tower to %s tower\n" , i , tower[begin] , tower[dest] );
else
{
hanoi ( i-1 , begin , dest , mid );
printf( "Move plate %d from %s tower to %s tower\n" , i , tower[begin] , tower[dest] );
hanoi( i-1 , mid , begin , dest );
}
return;
}
範例:
#include <stdio.h>
void main(void)
{
void func(void);
func();
}
void func(void)
{
printf("This is a non_stop program\n");
func(void);
}
執行結果
This is a non_stop program
This is a non_stop program
This is a non_stop program
This is a non_stop program
This is a non_stop pro^C (按下Ctrl + Break 才會中斷停止)
河內塔為常見例子。
河內塔計算程式
#include<stdio.h>
void hanoi ( int , int , int , int )
char tower [ ] [4] = { "1st" , "2nd" , "3rd" };
void main ( void )
{
int i;
printf( "How many plate (s) to move?" );
scanf( "%d" , &i );
hanoi( i , 0 , 1 , 2 );
}
void hanoi ( int i , int begin , int mid , int dest )
{
if (i==1)
printf ( "Move plate %d from %s tower to %s tower\n" , i , tower[begin] , tower[dest] );
else
{
hanoi ( i-1 , begin , dest , mid );
printf( "Move plate %d from %s tower to %s tower\n" , i , tower[begin] , tower[dest] );
hanoi( i-1 , mid , begin , dest );
}
return;
}
範例:
#include <stdio.h>
void main(void)
{
void func(void);
func();
}
void func(void)
{
printf("This is a non_stop program\n");
func(void);
}
執行結果
This is a non_stop program
This is a non_stop program
This is a non_stop program
This is a non_stop program
This is a non_stop pro^C (按下Ctrl + Break 才會中斷停止)
全站熱搜
留言列表