今日任务
- 24.两两交换链表中的节点
- 19.删除链表的倒数第N个节点
- 160. 链表相交
- 142.环形链表II
24.两两交换链表中的节点
题目链接:力扣-24.两两交换链表中的节点
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
提示:使用虚拟头节点,画图
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
res = ListNode(next = head) #dummy_head
pre = res
while pre.next and pre.next.next: #下面有两个可用节点时才可换
# 用两个辅助指针存储要交换的两个节点
cur = pre.next
post = pre.next.next
cur.next = post.next
post.next = cur
pre.next = post
pre = pre.next.next
return res.next
19.删除链表的倒数第N个节点
题目链接:力扣-19.删除链表的倒数第N个节点z
给你一个链表,删除链表的倒数第
n
个结点,并且返回链表的头结点。
提示:双指针
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
res = ListNode(next = head)
slow, fast = res, res
step = n
while step > 0:
fast = fast.next
step -= 1
while fast.next:
slow = slow.next
fast = fast.next
slow.next = slow.next.next
return res.next
160. 相交链表
题目链接:力扣-160.相交链表
给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。
注意,函数返回结果后,链表必须 保持其原始结构 。
提示:双指针,类似Q19
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
lenA, lenB = 0,0
cur = headA
while cur:
lenA += 1
cur = cur.next
cur = headB
while cur:
lenB += 1
cur = cur.next
curA, curB = headA, headB
if lenA >= lenB:
gap = lenA-lenB
while gap:
curA = curA.next
gap -= 1
else:
gap = lenB-lenA
while gap:
curB = curB.next
gap -= 1
while curA:
if curA == curB:
return curA
curA = curA.next
curB = curB.next
return None
142.环形链表II
题目链接:力扣-142.环形链表II
给定一个链表的头节点 head ,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
不允许修改 链表。
提示:慢指针从与快指针的相遇节点处出发与此时从头节点出发的另一慢指针相遇的位置
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
cur1 = head
cur2 = slow
while cur1 != cur2:
cur1 = cur1.next
cur2 = cur2.next
return cur1
return None