Go语言(Golang)约瑟夫游戏(Joseph)
生活随笔
收集整理的這篇文章主要介紹了
Go语言(Golang)约瑟夫游戏(Joseph)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
package mainimport ("fmt"
)//假設是一群小孩在玩這個游戲
//創建一個小孩的結構體
type BoyNode struct {No int //給每個小孩一個唯一的身份編號next *BoyNode //指向下一個小孩
}//假設有number個小孩在玩游戲
func AddBoyNode(number int) *BoyNode {head := &BoyNode {} //先創建一個頭節點temp := &BoyNode {} //創建一個輔助節點for i := 1; i<= number; i++ {boy := &BoyNode {No : i,}if i == 1 {head = boytemp = boytemp.next = head} else {temp.next = boytemp.next.next = head}temp = temp.next}return head
}//開始游戲
func Play(head *BoyNode, a, b int) *BoyNode {temp := head //輔助節點指向頭節點headhelper := head //輔助節點指向鏈表最后的節點//判斷如果沒有小孩無法游戲if temp.next == nil {fmt.Println("沒有小孩,無法進行游戲!")return head}//小孩只剩一個的時候退出游戲if temp.next == head {fmt.Println("只有一個小孩了,游戲結束!最后一個小孩為:")return head}//將helper指向最后一個小孩for {if helper.next == head {break}helper = helper.next}//循環找到從第a個小孩開始游戲for {if temp.No == a {break}temp = temp.nexthelper = helper.next}//數到b時出列的小孩for i := 1; i < b; i++ {temp = temp.nexthelper = helper.next}//如果該小孩是第一個小孩,則將頭節點指向下一個小孩if temp == head {head = head.next}helper.next = temp.nextfmt.Println()fmt.Printf("小男孩:%d出列!",temp.No)fmt.Println()ListBoyNode(head)//下一次游戲從第a個小孩開始a = temp.next.Noreturn Play(head,a,b)
}//輸出顯示鏈表
func ListBoyNode(head *BoyNode) {temp := headfor {fmt.Printf("小男孩:%d ==>",temp.No)temp = temp.nextif temp == head {break}}
}func main() {fmt.Println("請輸入有多少個小孩玩游戲:")var number intfmt.Scan(&number)head := AddBoyNode(number)ListBoyNode(head)fmt.Println("請輸入從第幾個小孩開始游戲:")var a int fmt.Scan(&a)fmt.Println("請輸入數幾的小男孩出列:")var b int fmt.Scan(&b)head = Play(head,a,b)ListBoyNode(head)
}
轉載于:https://www.cnblogs.com/HouZhenglan/p/10083697.html
總結
以上是生活随笔為你收集整理的Go语言(Golang)约瑟夫游戏(Joseph)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Jenkins Pipeline 构建复
- 下一篇: php静态变量