雙向鏈表
listvalue = [1, 5, 6, 2, 7, 3]
listright = [3, 2, 4, 5, -1, 1]
listleft = [-1, 5, 1, 0, 2, 3]
第一個列表爲鏈表元素,二三分別爲模擬指針,即對應結點指向左右的元素的位置
元素添加
被添加的元素b,前一個元素a,後一個元素c
第一步:給b左右的指針賦值,分別指向a,c。
第二步:給a的右指針,c的左指針賦值,指向b
兩步不能顛倒順序,否則鏈表斷開
元素刪除
元素刪除很簡單,將a的右指向c,c的左指向a即可
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 # 處理元素的前一個元素位置
def printlist(listv, listr, head):
print(listv[head])
next = listr[head]
while next != -1:
print(listv[next])
next = listr[next]
printlist(listvalue, listright, head)
print()
# 添加元素
listvalue.append(4)
listleft.append(prepos) # b左索引指向a
listright.append(listright[prepos]) # b右索引指向c
listright[prepos] = len(listvalue)-1
listleft[listright[len(listvalue)-1]] = len(listvalue)-1
printlist(listvalue, listright, head)
print()
# 刪除元素
listright[prepos] = listright[listright[prepos]]
listleft[listright[listright[prepos]]] = prepos
printlist(listvalue, listright, head)
print()