双向链表也叫双链表,是链表的一种,它的每个数据结点中都有两个指针,分别指向直接后继和直接前驱。所以,从双向链表中的任意一个结点开始,都可以很方便地访问它的前驱结点和后继结点。一般我们都构造双向循环链表。
代码实现:
# coding = utf-8
# 定义节点类
class Node(object):
def __init__(self, data):
# 定义数据域
self.data = data
# 定义后指向域
self.next = None
# 定义前指向域
self.prev = None
# 定义双向链表类
class Double_List(object):
def __init__(self):
# 定义链表头
self._head = Node(None)
# 定义链表长度
self._length = 0
def is_empty(self):
if self._length == 0:
return True
else:
return False
#循环遍历节点
def travel(self):
# 定义游标
cur = self._head
for i in range(self._length):
print(cur.next.data, end=" ")
cur = cur.next
else:
print(" ")
#尾部添加节点
def append(self, data):
# 构造新节点
new_code = Node(data)
# 创建游标
cur = self._head
for i in range(self._length):
# 移动游标
cur = cur.next
else:
# 插入新节点:
# 1.让新节点有所指向
new_code.prev = cur
# 2.让与新节点有关的节点有所指向
cur.next = new_code
# 链表长度加1
self._length += 1
def insert(self, pos, data):
# 判断pos有效性
if isinstance(pos, int):
if pos < 0:
dl.insert(0, data)
elif pos > self._length:
dl.append(data)
else:
# 创建新节点
new_code = Node(data)
# 创建游标
cur = self._head
for i in range(self._length):
if i == pos:
# 插入新节点:
# 1.让新节点有所指向
new_code.prev = cur
new_code.next =cur.next
# 2.让与新节点有关的节点有所指向
cur.next = new_code
new_code.next.prev =new_code
# 链表长度更新
self._length += 1
return
else:
cur = cur.next
else:
print("pos数据无效!")
def remove(self, data):
if self.is_empty():
print("list is empty")
else:
cur = self._head
for i in range(self._length):
if cur.next.data == data:
if cur.next.next is None:
# 尾部节点删除
cur.next = None
else:
# 删除中间节点
# 1.让中间节点前的节点的next指向中间节点的后节点
cur.next = cur.next.next
# 2.让中间节点后的节点的prev指向中间节点的前节点
cur.next.prev = cur
# 更新链表长度
self._length -= 1
return
else:
cur = cur.next
else:
print("{} is not in".format(data), end="")
if __name__ == "__main__":
print("尾部 插 入: ",end="")
dl = Double_List()
for i in range(10):
dl.append(i)
dl.travel()
print("任意位置插入:", end="")
dl.insert(-100, "a")
dl.insert(6, "x")
dl.insert(100, "z")
dl.travel()
print("删除 节 点 :",end="")
dl.remove("a")
dl.remove("x")
dl.remove("z")
dl.travel()
dl.remove("xxx")
dl.travel()
程序运行结果;
尾 部 插 入: 0 1 2 3 4 5 6 7 8 9
任意位置插入:a 0 1 2 3 4 x 5 6 7 8 9 z
删 除 节 点 :0 1 2 3 4 5 6 7 8 9
xxx is not in 0 1 2 3 4 5 6 7 8 9