约瑟夫问题——使用单向循环链表实现

面头条时被问到
有10个人围成一圈,给他们各自编号0~9,从0号开始数,数到3的人被杀,然后被杀的下一个人重新从1开始数,依次执行,直到剩下最后一个人。
解题思路:

  • 使用单向循环链表,按照报数的次数移动指针,到达报数的节点后将这个节点删除; 每次执行前先

  • 判断链表的长度,如果长度为1,那么代表找到了最后一个人

class Node(object):
    """节点"""

    def __init__(self, elem):
        """初始化节点"""
        # 存放元素内容
        self.val = elem
        # 存放下一个节点地址
        self.next = None


class SingleRecycleLinkList(object):
    """单向循环链表"""

    def __init__(self, N, node=None):
        """初始化"""
        self.__head = node
        # 传入的node不为空,指向自己
        if node:
            node.next = node
        # 创建有N个人的单向循环链表
        for i in range(N):
            self.append(i)

    def is_empty(self):
        """判断链表是否为空"""
        return self.__head == None

    def length(self):
        """链表长度"""
        if self.is_empty():
            return 0
        # cur游标,用来移动遍历节点
        cur = self.__head
        # count记录遍历的数量
        count = 1
        while cur.next != self.__head :
            count += 1
            cur = cur.next
        return count

    def travel(self):
        """遍历链表"""
        if self.is_empty():
            return
        cur = self.__head
        while cur.next != self.__head:
            print(cur.val, end=' ')
            cur = cur.next
        # 打印最后一个节点
        print(cur.val)

    def append(self, item):
        """尾部添加元素"""
        # 创建新的节点对象
        node = Node(item)
        # 判断当前链表是否为空
        if self.is_empty():
            self.__head = node
            node.next = node
        else:
            cur = self.__head
            # cur移动到末尾
            while cur.next != self.__head:
                cur = cur.next
            # cur的下一个指向新节点
            node.next = self.__head
            cur.next = node

    def find(self, M):
        pre = None
        cur = self.__head
        while True:
            for i in range(M-1):
                pre = cur
                cur = cur.next
            if cur == self.__head:
                # 判断是否是头结点
                end = self.__head
                while end.next != self.__head:
                    end = end.next
                self.__head = cur.next
                end.next = self.__head
                cur = self.__head
            else:
                pre.next = cur.next
                cur.prev = pre
                cur = pre.next
            self.travel()
            l = self.length()
            if l == 1:
                print(self.__head.val)
                break
# 创建对象,传递人数N            
s = SingleRecycleLinkList(10)
s.travel()
# 传递M值,找到最后或者的人
s.find(3)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值