defIsPalindrome(head):if head.nextisNone:returnTrue
slow = head
fast = head.nextwhile fast.nextisnotNoneand fast.next.nextisnotNone:
slow = slow.next
fast = fast.next.nextif fast.nextisnotNone:
slow = slow.next
fast = fast.next
new = reverse_one_directional_linkList(slow.next)L
p1 = head
p2 = new
while p2 isnotNone:if p2.value != p1.value:returnFalse
p2 = p2.next
p1 = p1.next
slow.next= reverse_one_directional_linkList(new)returnTrue
head = build_linkList([1,2])
IsPalindrome(head)
False
将单链表转化为:左边全部小于某个pivot,中间等于,右边大于的链表
defLinklist_for_partition(head, pivot):
LL, LR, EL, ER, HL, HR =None,None,None,None,None,None
p = head
while p isnotNone:
Next = p.next
p.next=Noneif p.value < pivot:if LL isNone:
LL = p
LR = p
else:
LR.next= p
LR = LR.nextelif p.value > pivot:if HL isNone:
HL = p
HR = p
else:
HR.next= p
HR = HR.nextelse:if EL isNone:
EL = p
ER = p
else:
ER.next= p
ER = ER.next
p = Next
# 背就行了 if LR isnotNone:
LR.next= EL
ER = ER if ER isnotNoneelse LR
if ER isnotNone:
ER.next= HL
return LL if LL isnotNoneelse EL if EL isnotNoneelse HL
head = build_linkList([4,4,3,4])
List = Linklist_for_partition(head,4)while List isnotNone:print(List.value)
List = List.next
3
4
4
4
有环链表判断入环节点
defIsLoopLinklist(head):if head isNoneor head.nextisNoneor head.next.nextisNone:returnFalse
f = head.next.next
s = head.nextwhile f != s:if f.nextisNoneand f.next.nextisNone:returnFalse
f = f.next.next
s = s.next
f = head
while f != s:
f = f.next
s = s.nextreturn s
defTwo_NoneLoop_Linklist(head1, head2):
p = head2
while p.nextisnotNone:
p = p.next
temp = p
p.next= head2
common = IsLoopLinklist(head1)
temp.next=Nonereturn common
defTwo_AllLoop_Linklist(head1, head2, loop1, loop2):
p1 = head1
p2 = head2
if loop1 is loop2:
n1 =1
n2 =1while p1 isnot loop1:
n1 +=1
p1 = p1.nextwhile p2 isnot loop2:
n2 +=1
p2 = p2.next
n =abs(n1-n2)
cur = head1 if n1>n2 else head2
p = head1 if cur isnot head1 else head2
while n >0:
cur = cur.next
n -=1while p isnot cur:
p = p.next
cur = cur.nextreturn cur
else:
cur = loop1.nextwhile cur isnot loop1:if cur is loop2:return loop2
cur = cur.nextreturnFalse