linux shell之不使用局部变量的递归

vi function14.sh
#!/bin/bash

#初始化移动次数
mov=0

dohanoi()
{
if [ $1 -eq 0 ] #输入圆盘的个数为0
then
echo -n "" #将不会有输出
else
dohanoi "$(($1-1))" $2 $4 $3 #把A上的n-1个圆盘移到B上
echo "move $2----->$3"

let "move=move+1" #把A上的一个圆盘移到C上
dohanoi "$(($1-1))" $4 $3 $2 #把B上的n-1个圆盘移到C上
fi

if [ $# -eq 1 ] #递归函数出口
then
if [ $(($1-1)) -eq 1] #至少要有一个圆盘
then
dohanoi $1 A C B
echo "Total moves = $move"
else
echo "The number of disk which you input is illegal!"
fi
fi
}


#脚本调用函数
echo "Please input the num of disk: "
read num
dohanoi $num ‘A‘ ‘B‘ ‘C‘

 

 

./function14.sh
Please input the num of disk:
4
move A----->C
move A----->B
move C----->B
move A----->C
move B----->A
move B----->C
move A----->C
move A----->B
move C----->B
move C----->A
move B----->A
move C----->B
move A----->C
move A----->B
move C----->B

linux shell之不使用局部变量的递归

上一篇:Linux系统下防火墙常用操作,开放端口等


下一篇:实现DataGridView行的拖动,即实现行的顺序交换