首页 > 其他 > 详细

链表问题(4)----环形链表

时间:2018-10-02 19:52:38      阅读:213      评论:0      收藏:0      [点我收藏+]

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)----环形链表

原文:https://www.cnblogs.com/Lee-yl/p/9736833.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!