以下为结点的定义:
class Node():
def __init__(self,value,next = None):
self.value = value
self.next = next
length = 0 #链表的长度,规定只有一个头结点时长度为0
判断链表是否为空:
def IsEmpty():
return length == 0
将结点Node插入到head之后:
def HeadInsert(head,node):
node.next = head.next
head.next = node
global length
length += 1
将结点插入到链表尾:
def TailInsert(head,node):
p = head
while p.next != None:
p = p.next
p.next = node
global length
length += 1
给一个结点,将新结点插入到给定结点之前:
def NodeInsert(oNode,node):
node.next = oNode.next
oNode.next = node
node.value,oNode.value = oNode.value,node.value
global length
length += 1
删除第index个结点:
def Delete(head,index):
global length
if index <= 0 or index > length:
print('index输错了。')
else:
p = head
i = 1
while i != index:
p = p.next
i += 1
p.next = p.next.next
length -= 1
快慢指针法找到链表的中间节点:
def FindMid(head):
f = head
s = head
index = 0
while f.next != None and f.next.next != None:
f = f.next.next
s = s.next
index += 1
return index