一种更复杂的链表叫“双向链表”或者“双面链表”,每个节点有两个链接,一个指向前一个节点,当此节点为第一个节点时,指向空值;而另一个指向下一个节点,当此节点为最后一个节点时,指向空值。
操作实现
class Node(object):
"""节点类"""
def __init__(self, item):
self.elem = item
self.prev = None
self.next = None
class DoubleLinkList(object):
"""双链表"""
def __init__(self, node=None):
self._head = node
def is_empty(self):
return self._head is None
def length(self):
"""链表长度"""
#cur游标,用来移动遍历节点
cur = self._head
#count记录数量
count = 0
while cur != None:
count = count + 1
cur = cur.next
return count
def travel(self):
"""遍历整个链表"""
#cur游标,用来移动遍历节点
cur = self._head
#count记录数量
while cur != None:
print(cur.elem,end=" ")
cur = cur.next
def add(self, item):
"""头部添加元素"""
node = Node(item)
node.next = self._head
self._head = node
node.next.prev = node #区别
def append(self, item):
"""尾部添加"""
node = Node(item)
#特殊处理,当前链表是否为空链表
if self.is_empty():
self._head = node
else:
cur = self._head
while cur.next != None: #游标移动循环过程
cur = cur.next
cur.next = node
node.prev = cur #区别
def insert(self, pos, item):
"""指定位置添加元素
param:pos,从0开始索引
"""
if pos < 0: #认为是头插法(add)
self.add(item)
elif pos > (self.length()-1):
self.append(item)
else:
cur = self._head
node = Node(item)
count = 0
while count < pos:
cur = cur.next
count += 1
#当循环结束后,cur指向pos位置(区别)
node.next = cur
node.prev = cur.prev
cur.prev.next = node
cur.prev = node
def remove(self, item):
"""删除节点"""
#用两个游标,一个游标同样可以pre.next = pre.next.next
cur = self._head
while cur != None:
if cur.elem == item:
#判断当前节点是否为头节点
#如果是头节点
if cur == self._head:
self._head = cur.next
if cur.next:
#判断链表只有一个节点
cur.next.prev = None
else:
cur.prev.next = cur.next
if cur.next:
cur.next.prev = cur.prev
break
else:
cur = cur.next
def search(self, item):
"""查找节点是否存在"""
cur = self._head
while cur != None:
if cur.elem == item:
return True
else:
cur = cur.next
return False
if __name__ == "__main__":
dll = DoubleLinkList()
print(dll.is_empty())
print(dll.length())
dll.append(1)
print(dll.is_empty())
print(dll.length())
dll.append(2)
dll.append(4)
dll.add(12)
dll.append(5)
dll.append(3)
dll.append(5)
dll.append(6)
dll.remove(12)
dll.append(4)
dll.insert(3,34)
dll.insert(-2,44)
dll.insert(15,55)
dll.travel()
结果
True
0
False
1
44 1 2 4 34 5 3 5 6 4 55