24. 两两交换链表中的节点
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
ret=head.next
while head and head.next:
n=head.next
if n.next and n.next.next:
nh=n.next.next
else:
nh=n.next
t=n.next
n.next=head
head.next=nh
head=t
return ret
19.删除链表的倒数第N个节点
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
t=ListNode(0,head)
f=t
s=t
for _ in range(n):
f=f.next
while f and f.next:
f=f.next
s=s.next
s.next=s.next.next
return t.next
面试题 02.07. 链表相交
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
if not headA or not headB:
return None
a=headA
b=headB
while a!=b:
if not a :
a=headB
else:
a=a.next
if not b :
b=headA
else:
b=b.next
return a
142.环形链表II
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
if not head or not head.next:
return None
f=head.next.next
s=head.next
while f and f.next and f.next.next and f!=s:
f=f.next.next
s=s.next
if not f or not f.next or not f.next.next:
return None
t=head
while t!=s:
t=t.next
s=s.next
return s