码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-10-02 20:29:44      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:结果   时间   return   elf   not   code   height   分享   复杂度   

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

标签:结果   时间   return   elf   not   code   height   分享   复杂度   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!