力扣_链表_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
相关推荐
小师兄吃牛肉1 分钟前
C语言篇:内联函数
c语言·开发语言
嘎嘎风3 分钟前
MiniMind 学习笔记之 07 模型怎么学会猜词(旋钮是怎么被拧动的)
算法·源码阅读
协皓家具11 分钟前
2026年广州岛台吧台椅厂家有啥新变化
大数据·运维·python·devops
yuniko-n18 分钟前
【Java】字符串相关坑点
java·开发语言·python
用户0190275816122 分钟前
如何用 Python 统计 A 股连续涨停(几连板)?
python
外收内放23 分钟前
Python基础语法练习题(拓展1)
python·游戏
和裕31 分钟前
定制纸箱刀模费全解析:费用定义与可减免合作场景
大数据·运维·网络·人工智能·算法
白山编程大哥35 分钟前
C语言篇:语法进阶
c语言·数据结构·算法
我命由我1234541 分钟前
Photoshop - Photoshop 面板和菜单
学习·职场和发展·产品运营·求职招聘·职场发展·产品经理·photoshop
jimy11 小时前
虚函数vtable,链接时看到构造函数,linker把符号地址写入vtable(三)
开发语言·c++