双向链表
一种更复杂的链表是“双向链表”或“双面链表”。每个节点有两个链接:一个指向前一个节点,当此节点为第一个节点时,指向空值;而另一个指向下一个节点,当此节点为最后一个节点时,指向空值。
实现
class Node(object): """双向链表节点""" def __init__(self, item): self.item = item self.next = None self.prev = None class DLinkList(object): def __init__(self): self.head = None def is_empty(self): return self.head is None def length(self): """返回链表的长度""" cur = self.head count = 0 while cur is not None: count += 1 cur = cur.next return count def travel(self): """遍历链表""" cur = self.head while cur is not None: print(cur.item) cur = cur.next print("遍历完了") 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 search(self, item): cur = self.head while cur is not None: if cur.item == item: return True cur = cur.next return False def insert(self, pos, item): """在指定位置添加节点""" if pos <= 0: self.add(item) elif pos > (self.length()-1): self.append(item) else: node = Node(item) cur = self.head count = 0 # 移动到指定位置的前一个位置 while count < (pos-1): count += 1 cur = cur.next # 先把node的关系设置好 node.prev = cur node.next = cur.next # 再配置cur的关系 cur.next.prev = node cur.next = node def remove(self, item): """删除元素,元素不存在不报错""" if self.is_empty(): return else: cur = self.head # 如果首节点是要删除的元素 if cur.item == item: if cur.next is None: # 如果链表只有这一个节点 self.head = None else: # 将第二个节点的prev设置为None cur.next.prev = None self.head = cur.next return # 遍历节点 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__': lst1 = DLinkList() lst1.add(1) lst1.add(2) lst1.append(3) lst1.insert(1, 4) lst1.travel() print(lst1.is_empty()) lst1.remove(2) lst1.travel() lst1.remove(10) lst1.travel()