力扣_链表_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
相关推荐
滋滋不吱吱16 分钟前
枚举中间位置基础篇
考研·算法·leetcode
阳光不锈@16 分钟前
算法:最长递增子序列解法记录
算法·最长递增子序列·超详细分析·java实现
遇见尚硅谷36 分钟前
C语言:20250728学习(指针)
c语言·开发语言·数据结构·c++·笔记·学习·算法
☆璇40 分钟前
【C++】C/C++内存管理
c语言·开发语言·c++
愿你天黑有灯下雨有伞1 小时前
枚举策略模式实战:优雅消除支付场景的if-else
java·开发语言·策略模式
网络安全打工人1 小时前
CentOS7 安装 rust 1.82.0
开发语言·后端·rust
楚轩努力变强1 小时前
前端工程化常见问题总结
开发语言·前端·javascript·vue.js·visual studio code
十八岁讨厌编程1 小时前
【算法训练营Day17】二叉树part7
算法
菜鸟学Python1 小时前
Python web框架王者 Django 5.0发布:20周年了!
前端·数据库·python·django·sqlite
梦想的初衷~1 小时前
MATLAB近红外光谱分析技术及实践技术应用
开发语言·支持向量机·matlab