前言
- 到了大章节【链表】了,争取两三天给它搞定!!
160. 相交链表 - 力扣(LeetCode)】
-
双指针
- 参考题解,相比于求长度+右对齐再一起出发的方法简洁多了
-
class Solution:def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:A, B = headA, headBwhile A != B:A = A.next if A else headB # A跑完就跳到B开始B = B.next if B else headA # B跑完就跳到A开始return A # 返回重合的节点或者返回空值
206. 反转链表 - 力扣(LeetCode)
-
双指针
-
class Solution:def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:pre, cur = None, headwhile cur:temp = cur.next # 暂存下一个节点cur.next = pre # 反转指针pre = cur # pre后移cur = temp # cur后移return pre # 最后cur是None,pre是最后的结点
-
234. 回文链表 - 力扣(LeetCode)
-
快慢指针 + 翻转
- 参考题解,复用上一题的翻转,注意一下奇偶以及最后要恢复链表
-
class Solution:def isPalindrome(self, head: Optional[ListNode]) -> bool:# 翻转链表def reverse(head):pre, cur = None, headwhile cur:temp = cur.nextcur.next = prepre = curcur = tempreturn pre# 快慢指针fast = slow = headwhile fast.next and fast.next.next:fast = fast.next.nextslow = slow.nextpre = slow # 存个pre断点方便恢复slow = slow.next # 后半截从中点的下一个节点开始left = headright = last = reverse(slow) # 存个last最后节点方便恢复while right: # 奇数right短一截,偶数right和left一样长if left.val != right.val:return Falseleft = left.nextright = right.next# 恢复链表pre.next = reverse(last)return True
后言
-
在工位刷题效率杠杠的!有双屏无论是编辑博文还是看题解都很舒服~ 链表真好玩呀(