虚拟头节点:
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next: return head
dummy_head = ListNode(0,head)
cur = head
pre = dummy_head
while cur and cur.next:
temp = cur.next.next
pre.next = cur.next
cur.next.next = cur
cur.next = temp
pre = cur
cur = temp
return dummy_head.next
递归:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
##递归的终止条件
if not head or not head.next: return head
##要进行交换的两个节点
pre = head
cur = pre.next
##记录要递归输入的节点
temp = pre.next.next
##两两交换
cur.next = pre
pre.next = self.swapPairs(temp)
return cur
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
dummy_head = ListNode(0,head)
fast = dummy_head
slow = dummy_head
for i in range(n+1):
fast = fast.next
while fast:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy_head.next
「链表 headA
」的节点数量为 a,「链表 headB
」的节点数量为 b ,「两链表的公共尾部」的节点数量为 c
- 头节点
headA
到node
前,共有 a - c个节点; - 头节点
headB
到node
前,共有 b −c个节点;
相遇时,headA共走a+(b−c),headB共走b+(a−c)
若两链表 有 公共尾部 (即 c>0) :指针 A , B 同时指向第一个公共节点 。
若两链表 无 公共尾部 (即 c=0) :指针 A , B 同时指向 null 。
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
a = headA
b = headB
while a!=b:
a = a.next if a else headB
b = b.next if b else headA
return a
- 问题一:判断链表是否环
- 问题二:如果有环,如何找到这个环的入口
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
fast = slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:##快慢指针相遇说明有环出现
fast = head
while fast!=slow:
fast = fast.next
slow = slow.next
return fast
return None
fast指针与slow指针相遇时,走的距离分别是x+y+z+y,x+y,且因为速度是二倍的关系
所以有x+y+z+y=2(x+y),即x=z。所以让fast指针指向头节点,fast和slow再相遇时即为环形的开始的第一个节点