首页 > 解决方案 > 将 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

标签: pythonpython-3.xlinked-list

解决方案


您想要的是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

推荐阅读