24. 两两交换链表中的节点
解题关键:
需要画图:
当前节点在交换节点之前一个。
需要使用两个临时值来保存数据。1点和3点
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy_head = ListNode(next= head)
curr = dummy_head
while curr.next and curr.next.next:
tem1 = curr.next
tem2 = curr.next.next.next
curr.next = curr.next.next
curr.next.next = tem1
tem1.next= tem2
curr = curr.next.next
return dummy_head.next
19.删除链表的倒数第N个节点
解题关键:
快指针比满指针多走n+1 个
当快指针不为空时,慢指针指向next.next
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
dummy_head = ListNode(next = head)
fast = 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
面试题 02.07. 链表相交
解题关键:
1、遍历链表的条件:while 链表还是while链表.next
while后面的条件是结束循环的条件,即不包括这个,如果结束条件是next则少遍历一个。
2、交换链表的时候不要忘记长度也要交换
3、计算完链表长度后记得链表归零
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
ln_A = headA
ln_B = headB
len_A,len_B=0,0
while ln_A:
ln_A=ln_A.next
len_A+=1
while ln_B:
ln_B=ln_B.next
len_B+=1
curr_A,curr_B=headA ,headB
if len_A>len_B:
curr_A,curr_B = headB,headA
len_A,len_B = len_B,len_A
for i in range(len_B-len_A):
curr_B=curr_B.next
while curr_B:
if curr_B==curr_A:
return curr_B
else:
curr_A=curr_A.next
curr_B=curr_B.next
return None
142.环形链表II
解题关键:快指针比慢指针多走一步,如果两者能相等,则说明有环,否则没有:
当两者相遇后,让慢指针回到原点,快慢指针再次相遇的位置即为环的起点。
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
fast = head
slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast==slow:
slow = head
while fast != slow :
slow= slow.next
fast = fast.next
return slow
return None