一、遍历单链表
1、使用两个列表方式实现
ListValue = [1, 5, 6, 2, 4, 3] # 存放链表每个元素的值
ListPointer = [3, 2, -1, 5, 1, 4] # 存放链表每个元素指向下一个元素的指针
head = 0
print(ListValue[head])
next = ListPointer[head]
while next != -1:
print(ListValue[next])
next = ListPointer[next]
2、使用一个嵌套列表方式实现
value = 0 # 代表链表值下标
pointer = 1 # 代表链表指针下标
LinkedList = [[1, 3], [5, 2], [6, -1], [2, 5], [4, 1], [3, 4]]
head = 0
print(LinkedList[head][value])
next = LinkedList[head][pointer]
while next != -1:
print(LinkedList[next][value])
next = LinkedList[next][pointer]
二、向单链表添加元素
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]
head = 0
prepos = 5 # 要插入的位置的上一个元素的位置
Output(ListValue, ListRight, head)
print('--------------')
ListValue.append(4) # 向数组末尾添加新元素4
ListRight.append(ListRight[prepos]) # 加上新元素指针指向的位置
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]
head = 0
prepos = 5 # 要插入的位置的上一个元素的位置
Output(ListValue, ListRight, head)
print('--------------')
ListRight[prepos] = ListRight[ListRight[prepos]]
Output(ListValue, ListRight, head)