while pa != pb: if pa == Noneand pb == None: returnNone elif pa == None: pa = headB pb = pb.next elif pb == None: pb = headA pa = pa.next else: pb = pb.next pa = pa.next return pa
判断链表是否包含环
判断链表是否包含环属于经典问题了,解决方案也是用快慢指针:
每当慢指针 slow 前进一步,快指针 fast 就前进两步。
如果 fast 最终遇到空指针,说明链表中没有环;如果 fast 最终和 slow 相遇,那肯定是 fast 超过了 slow 一圈,说明链表中含有环。
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution: defpartition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]: large_head = ListNode(0) small_head = ListNode(0) large = large_head small = small_head p = head while p isnotNone: if p.val < x: small.next = p small = p else: large.next = p large = p
p = p.next small.next = large_head.next large.next = None
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution: defmiddleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: fast = head slow = head while fast.nextisnotNone: if fast.nextisnotNone: fast = fast.next if fast.nextisnotNone: fast = fast.next if slow.nextisnotNone: slow = slow.next return slow
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution: defreverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: if head isNone: return head
p = head q = head.next head.next = None while q isnotNone: r = q.next q.next = p p = q q = r return p