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
相关推荐
咖啡配辣条24 分钟前
Python基础09
python
超大力王25 分钟前
DAY 45 超大力王爱学Python
开发语言·python
林-梦璃26 分钟前
Python开发基础手语识别(基础框架版)
开发语言·python·手语识别
RockyRich1 小时前
突然无法调用scikit-learn、xgboost
python·机器学习·scikit-learn
真的很上进1 小时前
2025最全TS手写题之partial/Omit/Pick/Exclude/Readonly/Required
java·前端·vue.js·python·算法·react·html5
敲键盘的小夜猫2 小时前
大模型智能体核心技术:CoT与ReAct深度解析
人工智能·python
圈圈编码2 小时前
LeetCode Hot100刷题——合并两个有序链表
java·数据结构·算法·leetcode·链表
华科云商xiao徐2 小时前
Python利用Scrapy框架部署分布式爬虫
python·scrapy
小前端大牛马2 小时前
java教程笔记(十四)-线程池
java·笔记·python
老歌老听老掉牙2 小时前
旋量理论:刚体运动的几何描述与机器人应用
python·算法·机器学习·机器人·旋量