1. 程式人生 > >鏈表問題(4)----環形鏈表

鏈表問題(4)----環形鏈表

__init__ png self 其中 elf one ini 普通 range

1、題目:環形單鏈表的約瑟夫問題

技術分享圖片

技術分享圖片

普通思路:時間復雜度O(n × m)

技術分享圖片

代碼:

技術分享圖片

技術分享圖片

class Node:
    def __init__(self,value):
        self.value = value
        self.next = None
def test(head,m):
    if not head or head.next == head or m < 2:
        return head
    # last = head
    # while last.next != head:
    #     last = last.next
count = 2 node = head while node.next != node: if count == m: # last = node.next node.next = node.next.next count = 1 node = node.next count += 1 head.next = None # head = node return node head = Node(1) head.next = Node(2) head.next.next
= Node(3) head.next.next.next = Node(4) head.next.next.next.next = Node(5) head.next.next.next.next.next = Node(6) head.next.next.next.next.next.next = Node(7) head.next.next.next.next.next.next.next = head m = 3 test(head,m)

遞歸思路:

從1人環的0計算到10人環,結果為4。轉化公式:

技術分享圖片

由圖知,10人環中最後入海的是4號,現由其在1人環中的對應編號0來求解。

公式:其中,m為報數值,i為第幾輪。

技術分享圖片

技術分享圖片

代碼:

class Node:
    def __init__(self,value):
        self.value = value
        self.next = None
def josephus(head,m):
    last = head
    n = 1
    while last.next != head:
        last = last.next
        n += 1
    fn = 0
    for i in range(2,n+1):
        fn = (fn + m) % i
    last = head
    if fn > 1:
        for i in range(fn-1):
            last = last.next
    pre = last.next 
    last.next = None
    pre.next = pre
    return pre
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
head.next.next.next = Node(4)
head.next.next.next.next = Node(5)
head.next.next.next.next.next = Node(6)
head.next.next.next.next.next.next = Node(7)
head.next.next.next.next.next.next.next = head
m = 3
josephus(head,m)

鏈表問題(4)----環形鏈表