力扣_链表_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
相关推荐
南棱笑笑生4 小时前
20250931在RK3399的Buildroot【linux-6.1】下关闭camera_engine_rkisp
开发语言·后端·scala·rockchip
christine-rr4 小时前
【25软考网工】第五章(11)【补充】网络互联设备
开发语言·网络·计算机网络·php·网络工程师·软考
Juan_20124 小时前
P3051题解
c++·数学·算法·题解
wyiyiyi4 小时前
【数据结构+算法】迭代深度搜索(IDS)及其时间复杂度和空间复杂度
数据结构·人工智能·笔记·算法·深度优先·迭代加深
404未精通的狗4 小时前
(数据结构)链表OJ——刷题练习
c语言·数据结构·链表
合作小小程序员小小店4 小时前
桌面预测类开发,桌面%性别,姓名预测%系统开发,基于python,scikit-learn机器学习算法(sklearn)实现,分类算法,CSV无数据库
python·算法·机器学习·scikit-learn·sklearn
Q26433650234 小时前
【有源码】基于Hadoop+Spark的豆瓣电影数据分析与可视化系统-基于大数据的电影评分趋势分析与可视化系统
大数据·hadoop·python·数据分析·spark·毕业设计·课程设计
洛_尘4 小时前
数据结构--4:栈和队列
java·数据结构·算法
Jiezcode5 小时前
LeetCode 138.随机链表的复制
数据结构·c++·算法·leetcode·链表