约瑟夫环
作者:互联网
基于python的约瑟夫环
思路一:递归
# 约瑟夫环:递归 def KillYuesefu(n,m): if(n == 1): return 0 return (KillYuesefu(n - 1, m) + m ) % n def main(): for num in range(1,11): lastindex=KillYuesefu(num,8)+1 print(lastindex) if __name__ == "__main__": main()
思路二:单向链表
# 约瑟夫环:单向循环链表 class Node: def __init__(self,Id,NextNode): self.Id=Id self.NextNode=NextNode def GenerateNodeLinkList(listLen): header = Node(1,None) tmpPreNode = header if(listLen < 1 ): return None elif listLen>1: for i in range(2,listLen): tmpNode = Node(i,None) tmpPreNode.NextNode=tmpNode tmpPreNode=tmpNode return header def GenerateNodeLinkList_Yuesefu(n): # 初始化链表 header = Node(1,None) tmpPreNode = header if(n < 1 ): return None elif n > 1: for i in range(2 , n+1): tmpNode = Node(i,None) tmpPreNode.NextNode=tmpNode tmpPreNode=tmpNode tmpPreNode.NextNode=header return header def KillYuesefu(nodelist,m): curIndex=1 curNode=nodelist preNode=None while(curNode!=preNode): if curIndex==m: # 杀死当前节点 print("%d" % (curNode.Id),end=" --> ") curNode=curNode.NextNode preNode.NextNode=curNode curIndex=1 else: curIndex=curIndex+1 preNode=curNode if curNode.NextNode is not None: curNode=curNode.NextNode else: break print("alive %d" % curNode.Id,end=" ") print("OVER") def main(): for num in range(1,11): print("begin num is %d" % num) nodelist=GenerateNodeLinkList_Yuesefu(num) KillYuesefu(nodelist,8) if __name__ == "__main__": main()
思路三:双向链表
# 约瑟夫环:双向循环链表 class Node: def __init__(self,Id,Name,PreNode,NextNode): self.Id=Id self.Name=Name self.PreNode=PreNode self.NextNode=NextNode def GenerateNodeLinkList(listLen): header = Node(1,"Name1",None,None) tmpPreNode = header if(listLen < 1 ): return None elif listLen>1: for i in range(2,listLen): tmpNode = Node(i,"Name-%d" % i,tmpPreNode,None) tmpPreNode.NextNode=tmpNode tmpPreNode=tmpNode return header def GenerateNodeLinkList_Yuesefu(n): # 初始化链表 header = Node(1,"Name1",None,None) tmpPreNode = header if(n < 1 ): return None elif n > 1: for i in range(2 , n): tmpNode = Node(i,"Name-%d" % i,tmpPreNode,None) tmpPreNode.NextNode=tmpNode tmpPreNode=tmpNode tmpPreNode.NextNode=header header.PreNode=tmpPreNode return header def KillYuesefu(nodelist,m): curIndex=1 curNode=nodelist while(curNode is not None): if curIndex==m: # 杀死当前节点 print("Id=%d,Name=%s" % (curNode.Id,curNode.Name),end=" --> ") tmp = curNode.PreNode if tmp is None: # 前面没有节点了,结束 break curNode=curNode.NextNode if tmp==curNode: # 重叠,结束 break tmp.NextNode=curNode curNode.PreNode=tmp curIndex=1 else: curIndex=curIndex+1 curNode=curNode.NextNode print("OVER") def main(): nodelist=GenerateNodeLinkList_Yuesefu(10) KillYuesefu(nodelist,6) if __name__ == "__main__": main()
标签:__,None,tmpPreNode,NextNode,约瑟夫,header,curNode 来源: https://www.cnblogs.com/lijunhao/p/15858437.html