24. 两两交换链表中的节点
用到了两个指针,一个pre,一个cur
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
res = ListNode(next=head)
pre = res#dummyhead
cur = res.next
while cur and cur.next:
tmp = cur.next.next
pre.next = cur.next
cur.next.next = cur
cur.next = tmp
pre = pre.next.next
cur = pre.next
return res.next
19. 删除链表的倒数第 N 个结点
快慢指针的思路;
快指针比慢指针快N个
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
dummy_head = ListNode(next = head)
slow = dummy_head
fast = dummy_head
while n:
fast = fast.next
n -= 1
while fast.next:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy_head.next
双指针
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
A, B = headA, headB
while A != B:#这里判断的是整个A/B后面指向的链表是否相同!
A = A.next if A else headB
B = B.next if B else headA
return A
快慢指针:
快指针每次走2,慢指针每次走1,快慢指针会相遇,则说明链表有环(最小公倍数)。
fast=slow,两个指针第一次相遇
slow指针同时从相遇位置和最开始位置出发,相遇的位置就是环的入口
公式理解:代码随想录
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
fast , slow = head , head
while fast != None:
fast = fast.next
if fast == None:
break
fast = fast.next#fast走2
slow = slow.next
if slow == fast:#第一次相遇
break
if fast==None:
return None
p,t = head,slow
while p!=t:
p = p.next
t = t.next
return p