defmidOrUpMid(head):ifnot head:return
slow = fast = head
while fast.nextand fast.next.next:
slow = slow.next
fast = fast.next.nextreturn slow
defvarifyMidOrUpMid(head):ifnot head:return
lst =[]
cur = head
while cur:
lst.append(cur)
cur = cur.nextreturn lst[(len(lst)-1)>>1]
2)输入链表头节点,奇数长度返回中点,偶数长度返回下中点
defmidOrDownMid(head):ifnot head ornot head.next:return head
slow = fast = head.nextwhile fast.nextand fast.next.next:
slow = slow.next
fast = fast.next.nextreturn slow
defvarifyMidOrDownMid(head):ifnot head:return
lst =[]
cur = head
while cur:
lst.append(cur)
cur = cur.nextreturn lst[(len(lst))>>1]
3)输入链表头节点,奇数长度返回中点前一个,偶数长度返回上中点前一个
defpreMidOrUpMid(head):ifnot head ornot head.nextornot head.next.next:return
slow = head
fast = head.next.nextwhile fast.nextand fast.next.next:
slow = slow.next
fast = fast.next.nextreturn slow
defvarifyPreMidOrUpMid(head):ifnot head:return
lst =[]
cur = head
while cur:
lst.append(cur)
cur = cur.nextiflen(lst)>2:return lst[(len(lst)-3)>>1]
4)输入链表头节点,奇数长度返回中点前一个,偶数长度返回下中点前一个
defpreMidOrDownMid(head):ifnot head ornot head.next:return
slow = head
fast = head.nextwhile fast.nextand fast.next.next:
slow = slow.next
fast = fast.next.nextreturn slow
defvarifyPreMidOrDownMid(head):ifnot head:return
lst =[]
cur = head
while cur:
lst.append(cur)
cur = cur.nextiflen(lst)>1:return lst[(len(lst)-2)>>1]
生成随机链表
defgenerateLinkedList(maxnum=20):import random
import string
num = random.randint(0, maxnum)if num ==0:returnNone
head = Node(random.choice(string.ascii_uppercase))
cur = head
for i inrange(1, num):
cur.next= Node(random.choice(string.ascii_uppercase))
cur = cur.nextreturn head