24. 两两交换链表中的节点
题目链接/文章讲解/视频讲解: 代码随想录
思路:使用虚拟头结点
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
dummy_head = ListNode(next=head)
current = dummy_head
# 必须有cur的下一个和下下个才能交换,否则说明已经交换结束了
while current.next and current.next.next:
temp = current.next # 防止节点修改
temp1 = current.next.next.next
current.next = current.next.next
current.next.next = temp
temp.next = temp1
current = current.next.next
return dummy_head.next
19.删除链表的倒数第N个节点
题目链接/文章讲解/视频讲解:代码随想录
思路:方法1 先遍历链表获取链表长度,再删除倒数第n个节点
方法2 使用快慢指针,先让快指针移动n+1个节点,然后快慢指针一起移动,直到快指针指向末尾的空节点,此时慢指针指向的即是倒数第n个节点的前一个节点,此时删除倒数第n个节点
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
# 创建一个虚拟节点,并将其下一个指针设置为链表的头部
dummy_head = ListNode(0, head)
# 创建两个指针,慢指针和快指针,并将它们初始化为虚拟节点
slow = fast = dummy_head
# 快指针比慢指针快 n+1 步
for i in range(n+1):
fast = fast.next
# 移动两个指针,直到快速指针到达链表的末尾
while fast:
slow = slow.next
fast = fast.next
# 通过更新第 (n-1) 个节点的 next 指针删除第 n 个节点
slow.next = slow.next.next
return dummy_head.next
142.环形链表II
题目链接/文章讲解/视频讲解:代码随想录
思路:快慢指针,若有环,两者定会相遇,此时新建一个变量从头结点开始移动,慢指针接着原链表移动,当两者相遇时,即为入环节点
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# If there is a cycle, the slow and fast pointers will eventually meet
if slow == fast:
# Move one of the pointers back to the start of the list
slow = head
while slow != fast:
slow = slow.next
fast = fast.next
return slow
# If there is no cycle, return None
return None