数据结构算法_环向链表
约瑟夫问题


package chapter05 import util.control.Breaks._ object test01 { def main(args:Array[String]):Unit={ val josephu = new Josephu() josephu.addBoy(5) josephu.countBoy(2,2,5) } } class Josephu{ //定义一个first,初始为null var first:Boy=null //小孩出圈 def countBoy(startNo:Int,countNum:Int,boyNums:Int):Unit={ //数据验证 if(first==null || startNo>boyNums || startNo<=0){ println("输入参数有误,无法开始游戏") return } //1. 创建辅助指针 var helper = first //2. 让helper移动到first的上一个 while(true){ if(helper.next == first){ break() } helper=helper.next } //3. 让first和helper再移动startNo-1个位置 for(i<-0 until startNo-1){ first = first.next helper = helper.next } //4.让first和helper再移动countNum-1个位置 //5.first指针就指向了要删除的位置 while(true){ for(i<-0 until countNum-1){ first = first.next helper = helper.next } printf("%d 出圈",first.no) first=first.next helper.next=first //判断是否只有一个小孩 if(first == helper){ break() } } printf("%d 幸运小孩",first.no) } //小孩出圈2 def countBoy2(startNo:Int,countNum:Int,boyNums:Int):Unit={ //数据验证 if(first==null || startNo>boyNums || startNo<=0){ println("输入参数有误,无法开始游戏") return } //1. 创建辅助指针 var helper = first //2. 让helper移动到first的上一个 while(true){ if(helper.next == first){ break() } helper=helper.next } //3. helper再移动startNo-1个位置 for(i<-0 until startNo-1){ helper = helper.next } //4.让helper再移动countNum-1个位置 //5.helper.next指针就指向了要删除的位置 while(true){ for(i<-0 until countNum-1){ helper = helper.next } printf("%d 出圈",helper.next.no) helper.next=helper.next.next //判断是否只有一个小孩 if(helper == helper.next){ break() } } printf("%d 幸运小孩",helper.no) } } class Boy(var no:Int,var next:Boy){ }
posted on 2020-08-24 11:59 happygril3 阅读(214) 评论(0) 收藏 举报
浙公网安备 33010602011771号