p
y
t
h
o
n
实
现
双
向
循
环
链
表
python实现双向循环链表
python实现双向循环链表
练习三部曲之一
class Node(object):
def __init__(self, elem):
self.elem = elem
self.next = None
self.prev = None
class DoubleCircleLinkedList(object):
def __init__(self, node=None):
self._head = node
def length(self):
if self.is_empty():
return 0
else:
cur = self._head.next
n = 1
while cur != self._head:
cur = cur.next
n += 1
return n
def is_empty(self):
return self._head is None
def addFirst(self, elem):
node = Node(elem)
if self.is_empty():
node.next = node
node.prev = node
self._head = node
else:
node.next = self._head
node.prev = self._head.prev
self._head.prev.next = node
self._head.prev = node
self._head = node
def addLast(self, elem):
if self.is_empty():
self.addFirst(elem)
else:
node = Node(elem)
cur = self._head.next
while cur.next != self._head:
cur = cur.next
cur.next = node
node.prev = cur
node.next = self._head
self._head.prev = node
def add(self, pos, elem):
if pos <= 0:
self.addFirst(elem)
elif pos >= self.length():
self.addLast(elem)
else:
cur = self._head.next
n = 1
while cur.next != self._head:
if n == pos:
break
cur = cur.next
n += 1
node = Node(elem)
node.prev = cur.prev
cur.prev.next = node
node.next = cur
cur.prev = node
def remove(self, elem):
if self.is_empty():
return
else:
if self._head.elem == elem:
if self.length == 1:
self._head = Node
else:
self._head.prev.next = self._head.next
self._head.next.prev = self._head.prev
self._head = self._head.next
cur = self._head.next
while cur != self._head:
if cur.elem == elem:
cur.prev.next = cur.next
cur.next.prev = cur.prev
cur = cur.next
def travel(self):
cur = self._head
while cur.next != self._head:
print(cur.elem, end=' ')
cur = cur.next
print(cur.elem)
def search(self, elem):
if self.is_empty():
return False
else:
cur = self._head.next
if self._head.elem == elem:
return True
else:
while cur != self._head:
if cur.elem == elem:
return True
else:
cur = cur.next
return False
练习三部曲之二
class Node(object):
def __init__(self, elem):
class DoubleCircleLinkedList(object):
def __init__(self, node=None):
def is_empty(self):
def addFirst(self, elem):
def addLast(self, elem):
def add(self, pos, elem):
def remove(self, elem):
def travel(self):
def search(self, elem):
练习三部曲之三
class DoubleCircleLinkedList(object):