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)
相关推荐
2301_764441332 小时前
LISA时空跃迁分析,地理时空分析
数据结构·python·算法
chushiyunen3 小时前
python rest请求、requests
开发语言·python
cTz6FE7gA3 小时前
Python异步编程:从协程到Asyncio的底层揭秘
python
baidu_huihui4 小时前
在 CentOS 9 上安装 pip(Python 的包管理工具)
开发语言·python·pip
南 阳4 小时前
Python从入门到精通day63
开发语言·python
lbb 小魔仙4 小时前
Python_RAG知识库问答系统实战指南
开发语言·python
FreakStudio4 小时前
MicroPython LVGL基础知识和概念:底层渲染与性能优化
python·单片机·嵌入式·电子diy
素玥5 小时前
实训5 python连接mysql数据库
数据库·python·mysql
zzzzls~5 小时前
Python 工程化: 用 Copier 打造“自我进化“的项目脚手架
开发语言·python·copier