面试算法之约瑟夫问题

面试算法之约瑟夫问题

题目:
在这里插入图片描述
一、构建环形链表

type Boy struct{
    
    
	num int
    next *Boy
}
func Add(num int) *Boy{
    
    
	temp:=&Boy{
    
    }
	help:=&Boy{
    
    }
	if num<1{
    
    
		fmt.Println("num数目小于1...")
		return temp
	}    //小于1无法构建链表
    for i:=1;i<=num;i++{
    
    
		 boy:=&Boy{
    
    
			 num:i,
		 }
        if i==1{
    
       //第一个节点,自己指向自己
			temp=boy
			help=boy
			help.next=temp
		}else{
    
    
			help.next=boy
			help=boy
			help.next=temp
		}
	}     //构建环形链表
	return temp
}

二、环形链表的展示

func Show(temp *Boy){
    
    
	first:=temp
	if first.next==nil{
    
    
		fmt.Println("环形链表的值为空...")
		return
	}
     for{
    
    
		 fmt.Printf("[%d]号->",first.num)
		 if first.next==temp{
    
    
			 break
		 }
		 first=first .next
	 }
}

三、约瑟夫问题实现

func PlayGame(first *Boy,startno int,countno int){
    
    
	if first.next==nil{
    
    
		fmt.Println("链表空空如也...")
	}
	help:=first
	for{
    
    
		if help.next==first{
    
    
			break
		}
		help=help.next
	}
	for i:=0;i<startno-1;i++{
    
    
		first=first.next
		help=help.next
	}
	for{
    
    
		for i:=0;i<countno-1;i++{
    
    
			first=first.next
			help=help.next
		}
		fmt.Printf("[%d]号->",first.num)
		first=first.next
		help.next=first
		if first==help{
    
    
			break
		}
	}
    fmt.Printf("[%d]号->",first.num)

}

四、主函数调用

func main(){
    
    
    temp:=Add(5)
	Show(temp)
	fmt.Println()
	fmt.Println("约瑟夫出列:")
	PlayGame(temp,2,3)
}

看完如果对自己有帮助,请点赞支持,谢谢

猜你喜欢

转载自blog.csdn.net/yyq1102394156/article/details/114273880