力扣_链表_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
相关推荐
shenyan~3 分钟前
关于 c、c#、c++ 三者区别
开发语言·c++
Ashlee_code15 分钟前
什么是Web3?金融解决方案
开发语言·金融·架构·eclipse·web3·区块链·php
weixin_3077791321 分钟前
批量OCR的GitHub项目
python·github·ocr
Evand J28 分钟前
【MATLAB例程】AOA与TDOA混合定位例程,适用于三维环境、4个锚点的情况,附下载链接
开发语言·matlab
机器视觉知识推荐、就业指导28 分钟前
Qt 与Halcon联合开发八: 结合Qt与Halcon实现海康相机采图显示(附源码)
开发语言·数码相机·qt
DoraBigHead1 小时前
小哆啦解题记——映射的背叛
算法
Heartoxx1 小时前
c语言-指针与一维数组
c语言·开发语言·算法
hqxstudying1 小时前
Java创建型模式---原型模式
java·开发语言·设计模式·代码规范
charlie1145141911 小时前
如何使用Qt创建一个浮在MainWindow上的滑动小Panel
开发语言·c++·qt·界面设计
孤狼warrior1 小时前
灰色预测模型
人工智能·python·算法·数学建模