力扣_链表_python版本

快慢指针

链表的快慢指针和数组的双指针或者相向双指针都是解决各自问题最基本的套路。

一、876. 链表的中间结点

  • 代码:
python 复制代码
class Solution:
    def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
        slow = head
        fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        return slow

二、141. 环形链表

  • 代码:
python 复制代码
class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        slow = fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if fast == slow:
                return True
        return False

三、142. 环形链表 II

  • 代码:
python 复制代码
class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        slow = fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow is fast:
                cur = head
                while cur != fast:
                    cur = cur.next
                    fast = fast.next
                return cur
        return None

四、143. 重排链表

  • 代码:
python 复制代码
def middleNode(head):
    slow = head
    fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
    return slow

def reverseList(head):
    pre = None
    cur = head
    while cur:
        nxt = cur.next
        cur.next = pre
        pre = cur
        cur = nxt
    return pre
    
class Solution:
    def reorderList(self, head: Optional[ListNode]) -> None:
        """
        Do not return anything, modify head in-place instead.
        """
        mid = middleNode(head)
        head2 = reverseList(mid)
        while head2.next:
            nxt = head.next
            nxt2 = head2.next
            head.next = head2
            head2.next = nxt
            head = nxt
            head2 = nxt2
相关推荐
一匹电信狗2 分钟前
【C++】哈希表详解(开放定址法+哈希桶)
服务器·c++·leetcode·小程序·stl·哈希算法·散列表
力江4 分钟前
攻克维吾尔语识别的技术实践(多语言智能识别系统)
人工智能·python·自然语言处理·语音识别·unicode·维吾尔语
诗句藏于尽头18 分钟前
MediaPipe+OpenCV的python实现交互式贪吃蛇小游戏
人工智能·python·opencv
007php00719 分钟前
某游戏大厂的常用面试问题解析:Netty 与 NIO
java·数据库·游戏·面试·职场和发展·性能优化·nio
北城以北888824 分钟前
SSM--MyBatis框架之动态SQL
java·开发语言·数据库·sql·mybatis
盼哥PyAI实验室32 分钟前
Python 正则表达式实战 + 详解:从匹配QQ邮箱到掌握核心语法
python·mysql·正则表达式
木易 士心33 分钟前
Android 开发核心技术深度解析
android·开发语言·python
迷途之人不知返38 分钟前
链表相关的算法题(2)
数据结构·算法·链表
nju_spy42 分钟前
力扣每日一题(四)线段树 + 树状数组 + 差分
数据结构·python·算法·leetcode·面试·线段树·笔试
程序员烧烤44 分钟前
【Java基础14】函数式接口、lamba表达式、方法引用一网打尽(下)
java·开发语言