前言
每日刷题,从己做起。
一、两两交换链表中节点
学会画图解题,弄懂实现交换的必备:添加虚拟头结点步骤。
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
res = ListNode(next = head)
pre = res
#必须有pre的下一个和下下个才能交换
while pre.next and pre.next.next:
cur = pre.next
post = pre.next.next
#pre, cur, post对应最左,中间的,最右边的节点
cur.next = post.next #1位置与3位置传递,
post.next = cur #2位置与1位置传递,
pre.next = post #pre位置与2位置传递,
pre = pre.next.next #更新pre位置
return res.next
二、删除链表中倒数第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: ListNode, n: int) -> ListNode:
head_pre = ListNode()
head_pre.next = head
slow, fast = head_pre, head_pre
while(n>=0): #移动fast走n步
fast = fast.next
n -= 1
while(fast!=None): #fast走到尽头即可更新此时二者位置
slow = slow.next
fast = fast.next
slow.next = slow.next.next #删除操作
return head_pre.next #不写成head的原因是head可能被删除
三、链表相交
代码如下(示例):
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
lenA, lenB = 0, 0
cur = headA
while cur: #求链表A的长度
cur = cur.next
lenA += 1
cur = headB
while cur: #求链表B的长度
cur = cur.next
lenB += 1
curA, curB = headA, headB
if lenA > lenB: #使curB为最长链表头,lenB为其长度
curA, curB = curB, curA
lenA, lenB = lenB, lenA
for _ in range (lenB - lenA):
curB = curB.next
while curA: #遍历A和B,相同及返回
if curA == curB:
return curA
else:
curA = curA.next
curB = curB.next
return None
四、环形链表II
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
#如果相遇
if slow == fast:
p = head
q = slow
while p != q:
p = p.next
q = q.next
return p
return None
总结
学会运用画图分析方法,认真理解代码,定时回顾已学内容。