45

利用单向环形链表解决约瑟夫问题

 5 years ago
source link: https://studygolang.com/articles/16623?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

利用单向环形链表解决约瑟夫问题

一开始我是想用list来解决的,但我想了很久都想不出来,只能用自定义的单向环形链表解决了。

基本思路: 略!!:smile:

直接上代码吧

//单向环形链表解决约瑟夫问题
package main

import "fmt"

//创建一个带自身指针的结构体
type node struct {
	no   int
	next *node
}

//创建两个标记变量,head标记第一个结点,tail标记最后一个结点
var head, tail *node

//追加结点
func addNode(n *node) {
	if tail == nil { 
		head = n
		n.next = head
		tail = n
	} else {
		tail.next = n
		n.next = head
		tail = n  //把链表最后一个的地址放到tail,即tail就是最后一个
	}
}

//约瑟夫环,从编号为k的人开始报数,数到num的那个人出列
func joseph(k, num int) {
	//记数变量
	count := 1

	//先移动到第k个人
	for i := 0; i < k-1; i++ {
		head = head.next
		tail = tail.next
	}

	//游戏从第k个人那里开始
	for {
		count++  //开始记数
		head = head.next
		tail = tail.next
		
		if count == num {
			//打印出数到num的人,并且让其出局
			fmt.Println(head.no, "号出局")
			tail.next = head.next
			head = head.next
			count = 1
		}

		//游戏剩最后一个人的时候结束
		if head == tail {
			fmt.Println(head.no, "号赢得了游戏")
			break
		}
	}
}

玩一波:

func main() {

	for i := 0; i < 5; i++ {
		n := &node{
			no: i + 1,
		}
		//追加结点
		addNode(n)
	}
	//从第一个人开始,数到3的那个人出列
	joseph(1, 3)

}

总结:golang自带的list是不是不能直接用来解决该问题(本人新手,望批评指正!!)

有哪位大神能用golang自带的list来解决吗?

如果确实不能用golang自带的list来解决,请给出个肯定的回答,好让我不要钻牛角尖


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK