# -*- coding=utf-8 -*-
# software: 算法学习
# datetime:2020/4/9 9:14 上午
class Node(object):
"""
链表的节点对象:包含数据与和指针域
"""
def __init__(self, data=None, next=None):
self._value = data
self._next = next
def get_value(self):
return self._value
def get_next(self):
return self._next
def set_value(self, new_data):
self._value = new_data
def set_next(self, new_next):
self._next = new_next
class CycleLinkList(object):
def __init__(self):
# 声明一个尾节点
self._tail = Node()
self._tail.set_next(self._tail)
self._length = 0
def head(self):
"""
链表的第一个元素(除去头节点)
:return:
"""
return self._tail.get_next()
def tail(self):
"""
链表的最后一个元素
:return:
"""
return self._tail
def is_empty(self):
"""
判断链表是否为空
:return:
"""
return self._tail.get_next() == self._tail
def size(self):
"""
链表的大小
:return:
"""
return self._length
def add(self, value):
"""
从头部插入节点
:param value:
:return:
"""
new_node = Node()
new_node.set_value(value)
new_node.set_next(self._tail.get_next())
self._tail.set_next(new_node)
self._length += 1
def append(self, value):
"""
从尾部追加节点
:param value:
:return:
"""
new_node = Node()
new_node.set_value(value)
new_node.set_next(self._tail)
head = self._tail.get_next()
tmp = head
while head != self._tail:
tmp = head
head = head.get_next()
tmp.set_next(new_node)
self._length += 1
def cycle(self, m):
"""
约瑟夫环
:return:
"""
str1 = ""
current = self._tail
tmp = self._tail
while current.get_next() != current:
count = m
for i in range(1, count + 1):
tmp = current
current = current.get_next()
if current == self._tail:
current = current.get_next()
tmp.set_next(current)
if current.get_next() == current:
break
tmp.set_next(current.get_next())
str1 += str(current.get_value()) + "-->"
return str1
def latin_policy(self, n):
"""
拉丁方阵
:param n:
:return:
"""
current = self._tail
tmp = self._tail
for i in range(n):
str1 = ""
for j in range(self.size()):
tmp = current
current = current.get_next()
str1 += str(current.get_value()) + " "
print(str1)
tmp = current
current = current.get_next()
if current == self._tail:
current = current.get_next()
tmp.set_next(current)
if __name__ == '__main__':
cycle_list = CycleLinkList()
for i in range(1, 6):
cycle_list.append(i)
current = cycle_list.tail().get_next()
tmp = cycle_list.tail()
l = ""
while current.get_next() != tmp:
l += str(current.get_value()) + " "
current = current.get_next()
l += str(current.get_value())
print("初始化遍历链表的值", l)
# 拉丁方阵
cycle_list.latin_policy(5)
# 死亡顺序
print(cycle_list.cycle(3))
拉丁方阵和约瑟夫环(链表)python
最新推荐文章于 2024-08-05 08:54:31 发布