循环链表(约瑟夫问题)--python实现

class Node:
    def __init__(self, value=None, next_addr=None):
        self._value = value
        self._next_addr = next_addr

    @property
    def next_addr(self):
        return self._next_addr

    @next_addr.setter
    def next_addr(self, addr):
        self._next_addr = addr

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, value):
        self._value = value

# 循环实现
# def check(first):
#     temp = first
#     i = 1
#     while temp != temp.next_addr.next_addr:
#         if i%2 == 0:
#             temp.next_addr = temp.next_addr.next_addr
#             temp = temp.next_addr
#             i += 1
#         else:
#             temp = temp.next_addr
#             i += 1
#
#     return temp.value, temp.next_addr.value


# 递归实现
def check(first):
    temp = first
    return s(temp, 1)

def s(node, count):

    temp = node
    if  temp == temp.next_addr.next_addr:
        return temp.value, temp.next_addr.value

    if count % 2 == 0:
        print(temp.next_addr.value)  # 删除的值
        temp.next_addr = temp.next_addr.next_addr
        temp = temp.next_addr
        return s(temp, count+1)
    else:
        temp = temp.next_addr
        return s(temp, count+1)


if __name__ == '__main__':
    j = Node(1)
    item = j
    for i in range(2, 42):
        item.next_addr = Node(i)
        item = item.next_addr

    item.next_addr = j

    print(check(j))

你可能感兴趣的:(算法与数据结构,算法,python)