python环形单链表的约瑟夫问题详解


Posted in Python onSeptember 27, 2018

题目:

一个环形单链表,从头结点开始向后,指针每移动一个结点,就计数加1,当数到第m个节点时,就把该结点删除,然后继续从下一个节点开始从1计数,循环往复,直到环形单链表中只剩下了一个结点,返回该结点。

这个问题就是著名的约瑟夫问题。

代码:

首先给出环形单链表的数据结构:

class Node(object):
 def __init__(self, value, next=0):
  self.value = value
  self.next = next # 指针

class RingLinkedList(object):
 # 链表的数据结构
 def __init__(self):
  self.head = 0 # 头部

 def __getitem__(self, key):
  if self.is_empty():
   print 'Linked list is empty.'
   return
  elif key < 0 or key > self.get_length():
   print 'The given key is wrong.'
   return
  else:
   return self.get_elem(key)

 def __setitem__(self, key, value):
  if self.is_empty():
   print 'Linked list is empty.'
   return
  elif key < 0 or key > self.get_length():
   print 'The given key is wrong.'
   return
  else:
   return self.set_elem(key, value)

 def init_list(self, data): # 按列表给出 data
  self.head = Node(data[0])
  p = self.head # 指针指向头结点
  for i in data[1:]:
   p.next = Node(i) # 确定指针指向下一个结点
   p = p.next # 指针滑动向下一个位置
  p.next = self.head

 def get_length(self):
  p, length = self.head, 0
  while p != 0:
   length += 1
   p = p.next
   if p == self.head:
    break
  return length

 def is_empty(self):
  if self.head == 0:
   return True
  else:
   return False

 def insert_node(self, index, value):
  length = self.get_length()
  if index < 0 or index > length:
   print 'Can not insert node into the linked list.'
  elif index == 0:
   temp = self.head
   self.head = Node(value, temp)
   p = self.head
   for _ in xrange(0, length):
    p = p.next
   print "p.value", p.value
   p.next = self.head
  elif index == length:
   elem = self.get_elem(length-1)
   elem.next = Node(value)
   elem.next.next = self.head
  else:
   p, post = self.head, self.head
   for i in xrange(index):
    post = p
    p = p.next
   temp = p
   post.next = Node(value, temp)

 def delete_node(self, index):
  if index < 0 or index > self.get_length()-1:
   print "Wrong index number to delete any node."
  elif self.is_empty():
   print "No node can be deleted."
  elif index == 0:
   tail = self.get_elem(self.get_length()-1)
   temp = self.head
   self.head = temp.next
   tail.next = self.head
  elif index == self.get_length()-1:
   p = self.head
   for i in xrange(self.get_length()-2):
    p = p.next
   p.next = self.head
  else:
   p = self.head
   for i in xrange(index-1):
    p = p.next
   p.next = p.next.next

 def show_linked_list(self): # 打印链表中的所有元素
  if self.is_empty():
   print 'This is an empty linked list.'
  else:
   p, container = self.head, []
   for _ in xrange(self.get_length()-1): #
    container.append(p.value)
    p = p.next
   container.append(p.value)
   print container

 def clear_linked_list(self): # 将链表置空
  p = self.head
  for _ in xrange(0, self.get_length()-1):
   post = p
   p = p.next
   del post
  self.head = 0

 def get_elem(self, index):
  if self.is_empty():
   print "The linked list is empty. Can not get element."
  elif index < 0 or index > self.get_length()-1:
   print "Wrong index number to get any element."
  else:
   p = self.head
   for _ in xrange(index):
    p = p.next
   return p

 def set_elem(self, index, value):
  if self.is_empty():
   print "The linked list is empty. Can not set element."
  elif index < 0 or index > self.get_length()-1:
   print "Wrong index number to set element."
  else:
   p = self.head
   for _ in xrange(index):
    p = p.next
   p.value = value

 def get_index(self, value):
  p = self.head
  for i in xrange(self.get_length()):
   if p.value == value:
    return i
   else:
    p = p.next
  return -1

然后给出约瑟夫算法:

def josephus_kill_1(head, m):
  '''
  环形单链表,使用 RingLinkedList 数据结构,约瑟夫问题。
  :param head:给定一个环形单链表的头结点,和第m个节点被杀死
  :return:返回最终剩下的那个结点
  本方法比较笨拙,就是按照规定的路子进行寻找,时间复杂度为o(m*len(ringlinkedlist))
  '''
  if head == 0:
   print "This is an empty ring linked list."
   return head
  if m < 2:
   print "Wrong m number to play this game."
   return head
  p = head
  while p.next != p:
   for _ in xrange(0, m-1):
    post = p
    p = p.next
   #print post.next.value
   post.next = post.next.next
   p = post.next
  return p

分析:

我采用了最原始的方法来解决这个问题,时间复杂度为o(m*len(ringlinkedlist))。
但是实际上,如果确定了链表的长度以及要删除的步长,那么最终剩余的结点一定是固定的,所以这就是一个固定的函数,我们只需要根剧M和N确定索引就可以了,这个函数涉及到了数论,具体我就不细写了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python中的并发编程实例
Jul 07 Python
在Python中处理列表之reverse()方法的使用教程
May 21 Python
简单学习Python time模块
Apr 29 Python
Python实现完整的事务操作示例
Jun 20 Python
Python下载网络文本数据到本地内存的四种实现方法示例
Feb 05 Python
python中的闭包函数
Feb 09 Python
python的dataframe转换为多维矩阵的方法
Apr 11 Python
Python文件读写保存操作的示例代码
Sep 14 Python
详解python破解zip文件密码的方法
Jan 13 Python
pytorch的batch normalize使用详解
Jan 15 Python
Django自定义全局403、404、500错误页面的示例代码
Mar 08 Python
anaconda python3.8安装后降级
Jun 11 Python
transform python环境快速配置方法
Sep 27 #Python
python如何求解两数的最大公约数
Sep 27 #Python
Python3中内置类型bytes和str用法及byte和string之间各种编码转换 问题
Sep 27 #Python
python斐波那契数列的计算方法
Sep 27 #Python
python实现汉诺塔算法
Mar 01 #Python
Python3中bytes类型转换为str类型
Sep 27 #Python
python求解数组中两个字符串的最小距离
Sep 27 #Python
You might like
在Windows中安装Apache2和PHP4的权威指南
2006/10/09 PHP
备份mysql数据库的php代码(一个表一个文件)
2010/05/28 PHP
php多文件上传功能实现原理及代码
2013/04/18 PHP
用PHP代替JS玩转DOM的思路及示例代码
2014/06/15 PHP
用php守护另一个php进程的例子
2015/02/13 PHP
JQuery 操作/获取table具体代码
2013/06/13 Javascript
js正则表达式中test,exec,match方法的区别说明
2014/01/29 Javascript
ext中store.load跟store.reload的区别示例介绍
2014/06/17 Javascript
javascript中Array数组的迭代方法实例分析
2015/02/04 Javascript
用nodeJS搭建本地文件服务器的几种方法小结
2017/03/16 NodeJs
bootstrap IE8 兼容性处理
2017/03/22 Javascript
微信小程序实战之轮播图(3)
2017/04/17 Javascript
Angular使用动态加载组件方法实现Dialog的示例
2018/05/11 Javascript
Vue axios设置访问基础路径方法
2018/09/19 Javascript
Angular8 Http拦截器简单使用教程
2019/08/20 Javascript
Python运维之获取系统CPU信息的实现方法
2018/06/11 Python
python3读取excel文件只提取某些行某些列的值方法
2018/07/10 Python
Flask模拟实现CSRF攻击的方法
2018/07/24 Python
Python 中的lambda函数介绍
2018/10/10 Python
python 分离文件名和路径以及分离文件名和后缀的方法
2018/10/21 Python
Python代码打开本地.mp4格式文件的方法
2019/01/03 Python
python数组循环处理方法
2019/08/26 Python
python爬虫-模拟微博登录功能
2019/09/12 Python
解决Jupyter notebook更换主题工具栏被隐藏及添加目录生成插件问题
2020/04/20 Python
将SVG图引入到HTML页面的实现
2019/09/20 HTML / CSS
非洲NO.1网上商店:Jumia肯尼亚
2016/08/18 全球购物
Coach澳大利亚官方网站:美国著名时尚奢侈品牌
2017/05/24 全球购物
Agoda西班牙:全球特价酒店预订
2017/06/03 全球购物
单位实习证明怎么写
2014/01/17 职场文书
六一儿童节活动策划方案
2014/01/27 职场文书
文明倡议书范文
2014/04/15 职场文书
高中班主任评语大全
2014/04/25 职场文书
教师节感恩老师演讲稿
2014/08/28 职场文书
小学生校园广播稿
2014/09/28 职场文书
出差报告怎么写
2014/11/06 职场文书
浅谈Web Storage API的使用
2021/06/23 Javascript