【代码随想录训练营】【Day 4】【链表2】| Leetcode 24, 19, 142, 面试题 02.07
需强化知识点
- 环形链表起点位置推导
题目
24. 两两交换链表中的节点
- 先确定交换对,记录前后节点,然后依次进行操作
- 注意要加 dummy_head
# 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]:
dummy_head = ListNode(next=head)
cur = head
prev = dummy_head
while cur and cur.next:
# node_a = cur
# node_b = cur.next
# tmp = cur.next.next
# prev.next = node_b
# node_b.next = node_a
# node_a.next = tmp
# cur = tmp
# prev = node_a
tmp = cur.next.next
prev.next = cur.next
cur.next.next = cur
cur.next = tmp
prev = cur
cur = tmp
return dummy_head.next
19. 删除链表的倒数第 N 个结点
- 快慢节点,快节点先走n步
- 注意要加dummy_head
# 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]:
dummy_head = ListNode(next=head)
slow, fast = dummy_head, dummy_head
for i in range(n):
fast = fast.next
while fast.next:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy_head.next
面试题 02.07. 链表相交
- 先计算A、B链表长度,短链表从head开始,长链表先走长度之差步(这一步是对齐尾部),然后依次前进,判定对应节点是否相等
# 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) -> ListNode:
lengthA, lengthB = 0, 0
curA, curB = headA, headB
while curA:
lengthA += 1
curA = curA.next
while curB:
lengthB += 1
curB = curB.next
curA, curB = headA, headB
if lengthA > lengthB:
for _ in range(lengthA-lengthB):
curA = curA.next
else:
for _ in range(lengthB-lengthA):
curB = curB.next
while curA != None and curB != None and curA != curB:
curA = curA.next
curB = curB.next
if curA != None and curB != None and curA == curB:
return curA
else:
return None
142. 环形链表 II
- 判定是否存在环:fast指针(每次走两步)和slow指针(每次走一步)是否相遇
- 判定环的起点:代码随想录
- 注意while的条件,如果未存在的环的情况
# 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]:
fast, slow = head, head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
cur = head
while cur != slow:
cur = cur.next
slow = slow.next
return cur
return None