迴圈連結串列(約瑟夫問題)--python實現

做個大暖男發表於2020-10-11
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))

相關文章