链表问题----环形链表
Posted lee-yl
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了链表问题----环形链表相关的知识,希望对你有一定的参考价值。
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)
以上是关于链表问题----环形链表的主要内容,如果未能解决你的问题,请参考以下文章