1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
//题目描述:N个小孩围成一圈玩游戏,游戏规则为:从第m个人开始报数,报到m的人出圈,剩下的人继续从1开始报数,报到m的人出圈;如此往复,直到所有人出圈。(模拟此过程,输出出圈的人的序号) package main import ( "fmt" "strconv" ) type children struct { no int name string nextChildren *children } /** 创建小孩函数 */ func createChildren(num int) *children{ first:=new(children) curent:=new(children) if num<1{ fmt.Println("数值不能小于1") return first } for i:=1;i<=num ;i++ { children:=&children{ no: i, name: "小孩"+strconv.Itoa(i)+"号", nextChildren: nil, } if i==1 { //小孩只有一个的时候,让他自己指向自己 first=children curent=children curent.nextChildren=first }else{ curent.nextChildren=children curent=children curent.nextChildren=first //构造环形链表 } } return first } /** 展示链表 */ func showList(head *children){ if head.nextChildren==nil{ fmt.Println("空链表,请先进行添加操作再展示") return } temp:=head for { fmt.Println(temp) if temp.nextChildren==head { break } temp=temp.nextChildren } } /** 进行游戏 */ func playgame(head *children,startNum,countNum int) { if head.nextChildren==nil{ fmt.Println("空链表,请先进行添加操作再开始游戏") return } //找到最后一个孩子 tail:=head for { if tail.nextChildren==head { break } tail=tail.nextChildren } for i:=1;i<=startNum-1;i++{ head=head.nextChildren tail=tail.nextChildren } for { for i:=1;i<=countNum-1;i++{ head=head.nextChildren tail=tail.nextChildren } fmt.Println("小孩",head.no,"出列") //执行删除该小孩操作 head=head.nextChildren tail.nextChildren=head if head.nextChildren==tail{ break } } fmt.Println("最后一个出列的孩子为",head.no) } func main() { headboy:=createChildren(5) showList(headboy) playgame(headboy,2,3) } |
© 著作权归作者所有
文章评论(0)