前言
- 到了大章节【链表】了,争取两三天给它搞定!!
160. 相交链表 - 力扣(LeetCode)】
-
哈希节点
- 存储A节点,遍历B查询
-
class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: mp = set() curA, curB = headA, headB while curA: mp.add(curA) curA = curA.next while curB: if curB in mp: return curB curB = curB.next return None
-
右对齐
- 分别计算A和B长度,长的先走相差长度步数,再一起前进
-
class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: curA, curB = headA, headB # 计算A和B的长度 lenA = lenB = 0 while curA: lenA += 1 curA = curA.next while curB: lenB += 1 curB = curB.next # 长的先走相差步数 curA, curB = headA, headB cha = max(lenA, lenB) - min(lenA, lenB) if lenA > lenB: while cha != 0: curA = curA.next cha -= 1 else: while cha != 0: curB = curB.next cha -= 1 # 一起走到相交/末尾None while curA != curB: curA = curA.next curB = curB.next return curA
-
双指针
- 参考题解,相比于求长度+右对齐再一起出发的方法简洁多了
-
class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: A, B = headA, headB while 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, head while 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: ListNode) -> bool: vals = [] cur = head while cur is not None: vals.append(cur.val) cur= cur.next return vals == vals[::-1] # 判断是否回文
-
-
快慢指针 + 翻转
- 参考题解,复用上一题的翻转,先用快慢指针找到中点和末尾,注意一下奇偶不同以及最后要恢复链表(可选)
-
class Solution: def isPalindrome(self, head: Optional[ListNode]) -> bool: # 翻转链表 def reverse(head): pre, cur = None, head while cur: temp = cur.next cur.next = pre pre = cur cur = temp return pre # 快慢指针 fast = slow = head while fast.next and fast.next.next: fast = fast.next.next slow = slow.next pre = slow # 存个pre断点方便恢复 slow = slow.next # 后半截从中点的下一个节点开始 left = head right = last = reverse(slow) # 存个last最后节点方便恢复 while right: # 奇数right短一截,偶数right和left一样长 if left.val != right.val: return False left = left.next right = right.next # 恢复链表 pre.next = reverse(last) return True
后言
-
在工位刷题效率杠杠的!有双屏无论是编辑博文还是看题解都很舒服~ 链表真好玩呀(