一、遍历双链表
ListValue = [1, 5, 6, 2, 7, 3]
ListRight = [3, 2, 4, 5, -1, 1]
ListLeft = [-1, 5, 1, 0, 2, 3]
# 正向遍历
head = ListLeft.index(-1)
print(ListValue[head])
next = ListRight[head]
while next > -1:
print(ListValue[head])
next = ListRight[head]
# 反向遍历
head = ListRight.index(-1)
print(ListValue[head])
next = ListLeft[head]
while next > -1:
print(ListValue[head])
next = ListLeft[head]
二、向双链表添加元素
def Output(ListValue, ListRight, head):
print(ListValue[head])
next = ListRight[head]
while next != -1:
print(ListValue[next])
next = ListRight[next]
ListValue = [1, 5, 6, 2, 7, 3]
ListRight = [3, 2, 4, 5, -1, 1]
ListLeft = [-1, 5, 1, 0, 2, 3]
head = 0
prepos = 5 # 要插入的位置的上一个元素的位置
Output(ListValue, ListRight, head)
print('--------------')
ListValue.append(4) # 向数组末尾添加新元素4
ListRight.append(ListRight[prepos]) # 给新元素的两个指针赋值
ListLeft.append(prepos)
ListRight[prepos] = len(ListValue) - 1 # 将前后元素的指针指向新元素
ListLeft[ListRight[prepos]] = len(ListValue) - 1
Output(ListValue, ListRight, head)
三、删除双链表元素
def Output(ListValue, ListRight, head):
print(ListValue[head])
next = ListRight[head]
while next != -1:
print(ListValue[next])
next = ListRight[next]
ListValue = [1, 5, 6, 2, 7, 3]
ListRight = [3, 2, 4, 5, -1, 1]
ListLeft = [-1, 5, 1, 0, 2, 3]
head = 0
prepos = 5 # 要插入的位置的上一个元素的位置
Output(ListValue, ListRight, head)
print('--------------')
ListRight[prepos] = ListRight[ListRight[prepos]]
ListLeft[ListRight[ListRight[prepos]]] = prepos
Output(ListValue, ListRight, head)