以下是实现约瑟夫环问题的Python代码列表:
使用循环列表:
def josephus(n, k): circle = [i for i in range(1, n+1)] idx = 0 while len(circle) > 1: idx = (idx + k - 1) % len(circle) circle.pop(idx) return circle[0]
使用循环链表:
class Node: def __init__(self, val): self.val = val self.next = None def josephus(n, k): head = Node(1) curr = head for i in range(2, n+1): curr.next = Node(i) curr = curr.next curr.next = head # make it a circular list prev = curr curr = head while prev.next != curr: for i in range(k-1): prev = curr curr = curr.next prev.next = curr.next curr = prev.next return curr.val
使用递归:
def josephus(n, k): if n == 1: return 1 else: return (josephus(n-1, k) + k-1) % n + 1
其中,n代表总人数,k代表报数的步长。函数返回最后留下的人的编号。
评论