我有一个LinkedList类,有近200行代码。我想通过始终确保任何myLL.tail.next is myLL.head
来做一个新的class LLCircular(LinkedList)
.我相信我需要相应地更新append()
、push()
、remove()
等。有没有办法做到这一点来保持原始的 LinkedList 类完好无损?也许是装饰器或某种下沉的方法?
为了简洁起见,如果阅读代码,我的push()
方法只是append()
的倒数。我还有一个pop()
和remove()
的方法,如果我只是重写这些方法,则需要更新。由于我试图避免这种方法,所以我不会发布代码的那部分。
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
你想要的是使用super
关键字调用你的LinkedList
基类函数,然后对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
如果它是"圆形的",它就不需要尾巴或头,对吗? "追加"也没有意义 - insert_after和insert_before方法应该足够了 - 此外,任何节点都是对完整循环列表的引用,不需要不同的对象:
class Circular:
def __init__(self, value=None):
self.value = value
self.next = self
self.previous = self
def insert_after(self, value):
node = Circular(value)
node.next = self.next
node.previous = self
self.next.previous = node
self.next = node
def insert_before(self, value):
node = Circular(value)
node.next = self
node.previous = self.previous
self.previous.next = node
self.previous = node
def del_next(self):
self.next = self.next.next
self.next.previous = self
def __iter__(self):
cursor = self.next
yield self
while cursor != self:
yield cursor
cursor = cursor.next
def __len__(self):
return sum(1 for _ in self)