LEETCODE 707. 设计链表

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

class MyLinkedList:

    def __init__(self):
        self.head=None
        self.size=0

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

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

    def addAtTail(self, val: int) -> None:
        if not self.head:
            self.addAtHead(val)
            return
        current_node=self.head
        while current_node.next:
            current_node=current_node.next
        current_node.next=ListNode(val)
        self.size+=1

    def addAtIndex(self, index: int, val: int) -> None:
        if index>self.size:
            return 
        if index<=0:
            self.addAtHead(val)
            return
        current_node=self.head
        for _ in range(index-1):
            current_node=current_node.next
        current_node.next=ListNode(val, current_node.next)
        self.size+=1
    def deleteAtIndex(self, index: int) -> None:
        if index<0 or index>=self.size:
            return
        self.size-=1
        
        if index==0:
            self.head=self.head.next
        else:
            current_node=self.head
            for _ in range(index-1):
                current_node=current_node.next
             
            current_node.next=current_node.next.next

# Your MyLinkedList object will be instantiated and called as such:
# obj = MyLinkedList()
# param_1 = obj.get(index)
# obj.addAtHead(val)
# obj.addAtTail(val)
# obj.addAtIndex(index,val)
# obj.deleteAtIndex(index)
相关推荐
ctlover34 分钟前
数据结构:树
数据结构·python
触底反弹1 小时前
🐍 Python 语法全景图:一个 print() 引发的深度探索
python
元Y亨H2 小时前
告别依赖地狱与打包崩溃:Python 项目环境治理与 PyInstaller 避坑实践
python
aramae2 小时前
Python 使用库:标准库与第三方库实战
服务器·开发语言·windows·python
IamZJT_2 小时前
Agent 系统工程 01|模型之外,Harness 到底该负责什么?
人工智能·python·程序员
沧海一笑-dj2 小时前
【Python】Python学习笔记-Python 核心基础
人工智能·python·ai·解释型语言
用户76855341255382 小时前
Python 并发怎么选?一篇讲清 threading、multiprocessing、asyncio 的边界
python
梦想不只是梦与想2 小时前
环境管理系统:Conda(一)
python·conda·环境隔离
计算机源码社3 小时前
基于K-Means聚类的新生儿败血症临床分型与可视化分析系统 基于数据挖掘的新生儿败血症生命体征时序走势与关联性可视化研究
大数据·hadoop·python·数据挖掘·数据分析·spark·毕业设计
一阵寒风3 小时前
用 AI 把PCB制前工程CAM无人值守输出系统做出来
python·ai编程·pcb工艺