python - 将 LinkedList 类转换为 Circular Linked List 类的最简单方法是什么?
问题描述
我有一个拥有近 200 行代码的 LinkedList 类。我想class LLCircular(LinkedList)
通过始终确保任何myLL.tail.next is myLL.head
. 我相信我需要相应地更新append()
, push()
,remove()
等。有没有办法让原始的 LinkedList 类保持完整?也许是一个装饰器或一些笨拙的方法?
为简洁起见,如果阅读代码,我的push()
方法只是append()
. 我还有一个pop()
andremove()
方法,如果我只是重写这些方法,则需要对其进行更新。因为我试图避免这种方法,所以我没有发布那部分代码。
class LinkedListNode:
def __init__(self, value, nextNode=None, prevNode=None):
self.value = value
self.next = nextNode
self.prev = prevNode
def __str__(self):
return str(self.value)
class LinkedList:
def __init__(self, values=None):
self.head = None
self.tail = None
if values is not None:
self.append(values)
def __str__(self):
values = [str(x) for x in self]
return ' -> '.join(values)
def append(self, value=None):
if value is None:
raise ValueError('ERROR: LinkedList.py: append() `value` PARAMETER MISSING')
if isinstance(value, list):
for v in value:
self.append(v)
return
elif self.head is None:
self.head = LinkedListNode(value)
self.tail = self.head
else:
''' We have existing nodes '''
''' Head.next is same '''
''' Tail is new node '''
self.tail.next = LinkedListNode(value, None, self.tail)
self.tail = self.tail.next
if self.head.next is None:
self.head.next = self.tail.prev
return self.tail
'''class LLCircular(LinkedList):'''
''' ??? '''
测试代码:
foo = LinkedList([1,2,3])
foo.tail.next = foo.head #My LL is now circular
cur = foo.head
i = 0
while cur:
print(cur)
cur = cur.next
i +=1
if i>9:
break
解决方案
您想要的是LinkedList
使用关键字调用您的基类函数super
,然后对LLCircular
类函数进行轻微修改,即:
class LLCircular(LinkedList):
def append(self, value=None):
super(LLCircular, self).append(value)
# In addition to having called the LinkedList append, now you want
# to make sure the tail is pointing at the head
self.tail.next = self.head
self.head.prev = self.tail
推荐阅读
- android - 如何使用数字墨水下载英文模型?
- mysql - MySQL where date on right join
- terraform-provider-azure - 有没有办法使用 terraform 或 arm 模板为突触配置 git?
- javascript - 从图表js中的数据数组连接工具提示
- typescript - 在不保留额外属性的情况下将类型与子类型匹配
- flutter - 杀死它后如何接收我的应用程序日志?
- python - 如何将 Marshmallow 中的 data_key 指定为可能的键名列表?
- android - 发出通知时如何在房间数据库中进行更改
- android - Android:如何在 API 28 以下的绘图中使用 LIGHTEN、DARKEN、OVERLAY Porter-Duff 模式
- javascript - 我们可以在javascript中有类似dos2unix的东西吗