File tree Expand file tree Collapse file tree 1 file changed +75
-1
lines changed
Expand file tree Collapse file tree 1 file changed +75
-1
lines changed Original file line number Diff line number Diff line change 163163
164164解法:
165165``` go
166- // 约瑟夫环
166+ // 约瑟夫环使用的无头结点循环链表结构:
167+ /* *
168+ * 循环链表:无头节点
169+ */
170+
171+ package list
172+
173+ import (
174+ " fmt"
175+ )
176+
177+ // 节点对象,存储循环链表上某个节点数据
178+ type node struct {
179+ Data interface {} // 数据域
180+ Next *node // 指针域
181+ }
182+
183+ // 循环链表对象:存储头指针与长度
184+ type NHRingList struct {
185+ Head *node
186+ Length int
187+ }
188+
189+ // 创建循环链表
190+ func New () *NHRingList {
191+ head := &node{nil , nil } // 头节点存储链表中元素的个数
192+ // head.Next = head // 循环指向自己
193+ return &NHRingList{
194+ head,
195+ 0 ,
196+ }
197+ }
198+
199+ // 增加:末尾添加
200+ func (rl *NHRingList ) Append (data interface{}){
201+
202+ insertNode := &node{data, rl.Head } // 要插入的节点
203+
204+ if rl.Length == 0 { // 第一次添加
205+ rl.Head = insertNode
206+ rl.Head .Next = insertNode
207+ } else { // 不是第一次添加
208+ tailNode := rl.Head
209+ for tailNode.Next != rl.Head {
210+ tailNode = tailNode.Next // 找到最后一个节点
211+ }
212+ tailNode.Next = insertNode
213+ }
214+
215+ rl.Length ++
216+ return
217+ }
218+
219+ // 打印链表
220+ func (rl *NHRingList ) Show () {
221+
222+ if rl.Length == 0 {
223+ fmt.Println (" list is empty" )
224+ return
225+ }
226+
227+ currentNode := rl.Head
228+ for i := 0 ; i <= rl.Length - 1 ; i++ {
229+ fmt.Print (currentNode.Data )
230+ if i == rl.Length - 1 {
231+ fmt.Print (" \n " )
232+ } else {
233+ fmt.Print (" " )
234+ }
235+
236+ currentNode = currentNode.Next
237+ }
238+ }
239+
240+ // 约瑟夫环问题解决
167241func testJosephus (){
168242
169243 // 第一步:生成没有头结点的环形链表
You can’t perform that action at this time.
0 commit comments