如何在已排序的双向链表中创建添加和删除功能

时间:2015-06-19 06:23:26

标签: python list doubly-linked-list sortedlist

以下是三个类:节点,双向链表和在双向链表上实现的排序列表。这是我的代码:

 class DLLNode(object):
  def __Init__ (self, data, prev_node=None, next_node=None):
    self.data=data
    self.prev_node=prev_node
    self.next_node=next_node

  def __str__(self):
    return str(self.data)

class DoublyLinkedList(object):
  def __init__(self, head=None, tail=None):
    self.head=head
    self.tail=tail
    self.size=0

  def add_to_head(self, data):
    newNode = DLLNode(data)
    if self.head==None:
      self.head=self.tail=newNode
      self.head.prev_node=self.tail.next_node=None
    else:
      self.head.prev_node=newNode
      newNode.next_node=self.head
      self.head=newNode

  def add_to_tail(self, data):
    newNode=DLLNode(data)
    if self.head==None:
      self.head=self.tail=newNode
      self.head.prev_node=self.tail.next_node=None
    else:
      self.tail.next_node=newNode
      newNode.prev_node=self.tail
      self.tail=newNode
      self.tail.next_node=None

  def remove_head(self):
    node=self.head
    if self.head==self.tail:
      self.prev_node=self.next_node=self.head=self.tail=None
      return
    if self.head!=self.tail:
      node=node.next_node
      node.prev_node=None
      self.head=node

  def remove_tail(self):
    node=self.tail
    if self.head==self.tail:
      self.prev_node=self.next_node=self.head=self.tail=None
      return
    if self.head!=self.tail:
      self.tail=node.prev_node
      self.tail.next_node=None


  def index(self,element):
    current = self.head
    while current != None:
      if current.data == element:
      return current.position
    else:
      current = current.next
      return -1
class SortedList(object):
  def __init__(self, sequence = []):
    if len(sequence)==0:
      self.head = None
      self.tail = None
    else:
      cur_node = None
      prev_node = None
      sequence.sort()
      sequence.reverse()
      for element in sequence:
        prev_node = cur_node
        cur_node = DLLNode(element, cur_node, prev_node)
        self.head = cur_node
        self.tail = DLLNode(sequence[0])

对于排序列表类,我需要创建一个添加和删除功能。但是,我真的不知道该怎么做。有人能告诉我吗?

0 个答案:

没有答案