leetcode707. 设计链表

leetcode707. 设计链表

题目

思路

1.使用虚头节点,模拟class的初始化

2.class中添加一个链表长度的属性,便于后续操作

代码

python 复制代码
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
        
class MyLinkedList:
    def __init__(self):
        self.dummy_head = ListNode()
        self.size = 0

    def get(self, index: int) -> int:
        if index < 0 or index >= self.size:
            return -1
        
        current = self.dummy_head.next
        for i in range(index):
            current = current.next
            
        return current.val

    def addAtHead(self, val: int) -> None:
        self.dummy_head.next = ListNode(val, self.dummy_head.next)
        self.size += 1

    def addAtTail(self, val: int) -> None:
        current = self.dummy_head
        while current.next:
            current = current.next
        current.next = ListNode(val)
        self.size += 1

    def addAtIndex(self, index: int, val: int) -> None:
        if index < 0 or index > self.size:
            return
        
        current = self.dummy_head
        for i in range(index):
            current = current.next
        current.next = ListNode(val, current.next)
        self.size += 1

    def deleteAtIndex(self, index: int) -> None:
        if index < 0 or index >= self.size:
            return
        
        current = self.dummy_head
        for i in range(index):
            current = current.next
        current.next = current.next.next
        self.size -= 1
相关推荐
xiaoxue..2 分钟前
二叉树深度解析:从基础结构到实战应用
javascript·数据结构·面试
道19932 分钟前
PyTorch 高级进阶教程之深度实战实例(四)
人工智能·pytorch·python
hbqjzx8 分钟前
[工具] B站油管DY视频下载器 2025.12.18
python
自己的九又四分之三站台11 分钟前
基于Python获取SonarQube的检查报告信息
开发语言·python
彼岸花开了吗13 分钟前
构建AI智能体:五十七、LangGraph + Gradio:构建可视化AI工作流的趣味指南
人工智能·python
weixin_3954489120 分钟前
TDA4工程和tda2工程相比,数据预处理部分tda4有哪些升级?带来了什么好处,tda2原来的数据预处理有哪些坏处
人工智能·python·机器学习
luoluoal27 分钟前
基于python的des算法的企业用户数据安全软件(源码+文档)
python·mysql·毕业设计·源码
Mqh18076228 分钟前
day43 图像数据与现存
python
逻极28 分钟前
Python MySQL监控与日志配置实战:从“盲人摸象”到“明察秋毫”
python·mysql·监控·日志
风筝在晴天搁浅31 分钟前
hot100 3.无重复字符的最长子串
数据结构·算法·leetcode