实现双链表需要注意的地方
1、如何插入元素,考虑特殊情况:头节点位置,尾节点位置;一般情况:中间位置
2、如何删除元素,考虑特殊情况:头结点位置,尾节点位置;一般情况:中间位置
代码实现
- 构造节点的类和链表类
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.previous = None
class DoubleLinkList:
'''双链表'''
def __init__(self, node=None):
self._head = node
以下方法均在链表类中实现
2. 判断链表是否为空
def is_empty(self):
return self._head is None
- 输出链表的长度
def length(self):
count = 0
if self.is_empty():
return count
else:
current = self._head
while current is not None:
count += 1
current = current.next
return count
- 遍历链表
def travel(self):
current = self._head
while current is not None:
print("{0}".format(current.data), end=" ")
current = current.next
print("")
- 头插法增加新元素
def add(self, item):
node = Node(item)
# 如果链表为空,让头指针指向当前节点
if self.is_empty():
self._head = node
# 注意插入的顺序,
else:
node.next = self._head
self._