双向链表的特性:元素的由他的值和链各个指针组成,左指针指向上一元素, 右指针指向下一元素
class Node(object):
def __init__(self, item):
self.item = item
self.next = None
self.prev = None
class DoubleLink(object):
def __init__(self):
self.head = None
def is_empty(self):
return self.head == None
def lenght(self):
cur = self.head
count = 0
while cur != None:
count += 1
cur = cur.next
return count
def travel(self):
"""遍历单链表"""
if self.is_empty():
return None
else:
cur = self.head
while cur is not None:
cur = cur.next
def add(self, item):
"""向单链表头部添加节点"""
node = Node(item)
if self.is_empty():
self.head = node
else:
node.next = self.head
self.head.prev = node
self.head = node
def append(self, item):
"""向单链表尾部添加节点"""
node = Node(item)
if self.is_empty():
self.head = node
else:
cur = self.head
while cur.next is not None:
cur = cur.next
cur.next = node
node.prev = cur
def insert(self, item, pos):
if pos >= self.lenght():
self.append(item)
elif pos <= 0:
self.add(item)
else:
cur = self.head
node = Node(item)
count = 0
while count < pos - 1:
count += 1
cur = cur.next
node.next = cur.next
node.prev = cur
cur.next.prev = node
cur.next = node
def search(self, item):
if self.is_empty():
return None
else:
cur = self.head
while cur is not None:
if cur.item == item:
return True
cur = cur.next
return False
def remove(self, item):
if self.is_empty():
return Node
else:
cur = self.head
if cur.item == item:
if cur.next is None:
self.head = Node
else:
cur.next.prev = None
self.head = cur.next
return True
while cur is not None:
if cur.item == item:
cur.prev.next = cur.next
cur.next.prev = cur.prev
break
cur = cur.next
if __name__ == '__main__':
dl = DoubleLink()
print(dl.is_empty())
print(dl.lenght())
dl.add(1)
dl.add(2)
dl.add(3)
dl.append(4)
dl.append(5)
dl.insert(6, 4)
dl.insert(7, 5)
dl.insert(7, 9)
dl.insert(8, 0)
dl.remove(8)
dl.travel()
print(dl.search(8))