力扣_链表_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
相关推荐
方案开发PCBA抄板芯片解密8 分钟前
什么是算法:高效解决问题的逻辑框架
算法
songx_9919 分钟前
leetcode9(跳跃游戏)
数据结构·算法·游戏
上位机付工26 分钟前
C#与倍福TwinCAT3进行ADS通信
开发语言·c#
学c语言的枫子29 分钟前
数据结构——双向链表
c语言·数据结构·链表
励志不掉头发的内向程序员36 分钟前
STL库——二叉搜索树
开发语言·c++·学习
小白狮ww1 小时前
RStudio 教程:以抑郁量表测评数据分析为例
人工智能·算法·机器学习
AAA修煤气灶刘哥1 小时前
接口又被冲崩了?Sentinel 这 4 种限流算法,帮你守住后端『流量安全阀』
后端·算法·spring cloud
至此流年莫相忘1 小时前
设计模式:模板方法模式
java·开发语言·设计模式
土了个豆子的1 小时前
02.继承MonoBehaviour的单例模式基类
开发语言·visualstudio·单例模式·c#·里氏替换原则
qq_172805592 小时前
Go 自建库的使用教程与测试
开发语言·后端·golang