5-单向环形链表-Scala实现

单向环形链表可以解决约瑟夫问题(丢手帕问题),记录一下代码

package com.atguigu.datastructures.linkedList
import scala.util.control.Breaks._
object Josephu {
  def main(args: Array[String]): Unit = {
      val game = new BoyGame()
      game.addBoy(5)
   //   game.showBoy()
      game.countBoy(2,2,5)
  }

}
class Boy(bNo:Int){
  val no:Int = bNo
  var next:Boy = null
}
class BoyGame{
  var first:Boy = new Boy(-1)
  def addBoy(nums:Int):Unit={
    if (nums<1){
      println("nums的值不正确")
      return
    }
    var curBoy:Boy = null
    for(no <- 1 to nums){
      val boy=new Boy(no)
      if (no==1){
        first=boy
        first.next=first
        curBoy=first
      }else{
        curBoy.next=boy
        boy.next=first
        curBoy=boy
      }
    }
  }

  def countBoy(start:Int,count:Int,nums:Int):Unit={
    if (first.next == null || start<1 || start>nums){
      println("参数有误")
      return
    }
    //创建辅助指针
    var helper = first
    //让helper移动first上一个
    breakable {
      while (true) {
        if (helper.next == first) {
          break()
        }
        helper = helper.next
      }
    }
    //让first移动k-1个位置,同时helper也相应移动

    for(i <- 0 until start-1){
      first = first.next
      helper = helper.next
    }
    breakable {
      while (true) {
        for (i <- 0 until count - 1) {
          //for循环结束,first就指向要删除的小孩
          first = first.next
          helper = helper.next
        }
        //删除该小孩
        printf("小孩no=%d出圈\n", first.no)
        first = first.next
        helper.next = first
        //判断是否只有一个小孩了
        if (first == helper) {
          break()
        }
      }
    }
    printf("最后留在圈中小孩为:%d\n",first.no)

  }


  def showBoy():Unit={
    if (first.next == null){
      println("没有任何小孩")
      return
    }
    var curBoy = first
    breakable{
      while (true){
        printf("小孩编号 %d\n",curBoy.no)
        if (curBoy.next == first){
          break()
        }
        curBoy = curBoy.next
      }
    }
  }
}

  

posted @ 2020-05-21 22:43  济默  阅读(160)  评论(0编辑  收藏  举报