约瑟夫环问题 python

方法一:链表实现

class Node:
    def __init__(self,item):
        self.next = None
        self.val = item

class Solution:
    def Circle(self,n,m):
        alist = []
        for i in range(n):
            alist.append(i)
        node = Node(alist[0])
        pHead = node
        index = pHead
        for i in range(1,n):
            node1 = Node(alist[i])
            index.next = node1
            index = node1
        index.next = pHead
        count = n
        index = pHead
        while(count>1):
            for i in range(1,m-1):
                index = index.next
            temp = index.next
            # print(temp.val)
            alist.remove(temp.val)
            index.next = temp.next
            index = index.next#!!!
            count -= 1
        return alist[0]
s= Solution()
p =s.Circle(7,3)
print(p)```

你可能感兴趣的:(Python,牛客网)