力扣_链表_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
相关推荐
道剑剑非道2 分钟前
Qt【使用libmodbus库】
开发语言·数据库·qt
白兰地空瓶4 分钟前
你以为树只是画图?不——它是算法面试的“隐形主角”
前端·javascript·算法
csbysj20207 分钟前
PHP 函数
开发语言
好易学·数据结构14 分钟前
可视化图解算法74:最小花费爬楼梯
数据结构·算法·leetcode·动态规划·力扣
BoBoZz1923 分钟前
Glyph2D 同一个图形根据点云的输入产生不同位置的输出
python·vtk·图形渲染·图形处理
一笑code25 分钟前
pycharm vs vscode安装python的插件
vscode·python·pycharm
_w_z_j_29 分钟前
Linux----线程互斥与同步
linux·运维·开发语言
云栖梦泽30 分钟前
易语言网络编程基础:构建网络版应用
开发语言
liwulin050637 分钟前
【PYTHON-YOLOV8N】yoloface+pytorch+cnn进行面部表情识别
python·yolo·cnn
Maỿbe39 分钟前
力扣hot图论部分
算法·leetcode·图论