思路
约瑟夫环问题 : 题目是 假设有N个小朋友按顺序围成一圈,每个小朋友都有一个编号,假设从第m个小朋友从1开始报数,报到k的小朋友出圈,从出圈的下一个小朋友继续报数,重复上面的报数。直到所有的人出圈位置。 求出圈的小朋友的顺序是什么
解决方案: 我们使用的是单向的环形链表作为数据结构 思路大致分为
寻找指定开始节点跳动指定的步长-1(需要获取弹出节点的前一个节点,才可以做删除)显示弹出节点
代码
package com
.xipenhui
.cn
import scala
.collection
.mutable
.ArrayBuffer
import scala
.util
.control
.Breaks
._
object JosephuDemo
{
def main
(args
: Array
[String]): Unit = {
val josephu
= new Josephu
()
val boys
= josephu
.addBoy
(5)
println
("=======创建出来的boys是=======")
josephu
.show
()
println
("===弹出小朋友===")
josephu
.popBoy
(2,3,5)
}
}
class Josephu
{
var head
= Boy
(-1)
def addBoy
(num
: Int) {
if (num
< 1) {
throw new RuntimeException
("input num must big than 1")
}
var currBoy
: Boy
= null
for (i
<- 1 to num
) {
val boy
= new Boy
(i
)
if (i
== 1) {
head
= boy
head
.next
= head
currBoy
= boy
} else {
currBoy
.next
= boy
boy
.next
= head
currBoy
= boy
}
}
}
def popBoy
(startNum
: Int, countNum
: Int, len
: Int): Unit = {
if (head
.next
== null || startNum
< 1 || startNum
> len
) {
println
("输入参数错误,请重新输入")
System
.exit
(0)
}
var currBoy
: Boy
= head
breakable
{
while (currBoy
.next
!= head
) {
if (currBoy
.num
== startNum
) {
break
()
} else {
currBoy
= currBoy
.next
}
}
}
if (currBoy
.next
== head
) throw new RuntimeException
("can not find input element")
for (i
<- 0 until len
) {
for (j
<- 1 until countNum
-1) {
currBoy
= currBoy
.next
}
print
(s
"output element is ${currBoy.next.num} \n")
currBoy
.next
= currBoy
.next
.next
currBoy
= currBoy
.next
}
}
def show
(): Unit = {
var currBoy
= head
while (currBoy
.next
!= head
){
println
(s
"input boy's num is ${currBoy.num}")
currBoy
=currBoy
.next
}
println
(s
"input boy's num is ${currBoy.num}")
}
}
case class Boy
(num
: Int) {
var next
: Boy
= null
}