力扣_链表_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
相关推荐
郝学胜-神的一滴几秒前
Python 高级编程 019:类变量与实例变量彻底解析
开发语言·python·程序人生·软件构建
退休倒计时8 分钟前
【每日一题】LeetCode 15. 三数之和 TypeScript
数据结构·算法·leetcode·typescript
林爷万福14 分钟前
MATLAB光谱数据分析从入门到项目实战
算法·光纤光谱仪
CTA量化套保18 分钟前
期货量化临期合约还能不能做:程序化到期禁开与强平写法
python·区块链
吴可可12321 分钟前
AutoCAD2016二次开发环境配置指南
算法·机器学习
Thomas_YXQ21 分钟前
Unity3D Addressable 深度优化热更性能消耗
开发语言·3d·unity·微信
一条大祥脚24 分钟前
ABC461 枚举|扫描线|动态前缀和|数论|dfs枚举子集
算法·深度优先
aini_lovee25 分钟前
C# 快递单打印系统(万能套打系统)
开发语言·c#
计算机安禾27 分钟前
【数据库系统原理】第14篇:关系模式的语义约束:函数依赖的公理系统与闭包计算
人工智能·算法·机器学习
量化君也28 分钟前
快速入门量化交易都要学些什么?
大数据·人工智能·python·算法·金融