Python and python
Joseph's ring problem: n people (represented by numbers 1, 2, 3... n) are known to be sitting around a round table. The number of people numbered k starts to report, and the person whose number is k is killed; the person whose number is k starts to report data from 1, and the person whose number is k is killed again; repeat this rule until there is only one person around the Round Table.
The idea is: when k is 1, the last person is alive. When k> = 2, construct a circular linked list with n elements, and then kill the k users in turn, the last one left is a person who can survive. The Code is as follows:
class Node():def __init__(self,value,next=None):self.value=valueself.next=nextdef createLink(n):if n<=0:return Falseif n==1:return Node(1)else:root=Node(1)tmp=rootfor i in range(2,n+1):tmp.next=Node(i)tmp=tmp.nexttmp.next=rootreturn rootdef showLink(root):tmp=rootwhile True:print(tmp.value)tmp=tmp.nextif tmp==None or tmp==root:breakdef josephus(n,k):if k==1:print('survive:',n)returnroot=createLink(n)tmp=rootwhile True:for i in range(k-2):tmp=tmp.nextprint('kill:',tmp.next.value)tmp.next=tmp.next.nexttmp=tmp.nextif tmp.next==tmp:breakprint('survive:',tmp.value)if __name__=='__main__':josephus(10,4)print('-----------------')josephus(10,2)print('-----------------')josephus(10,1)print('-----------------')
The output result is as follows:
Reprinted Please note: