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)
相关推荐
Java后端的Ai之路10 小时前
【Python 教程15】-Python和Web
python
冬奇Lab12 小时前
一天一个开源项目(第15篇):MapToPoster - 用代码将城市地图转换为精美的海报设计
python·开源
二十雨辰14 小时前
[python]-AI大模型
开发语言·人工智能·python
Yvonne爱编码14 小时前
JAVA数据结构 DAY6-栈和队列
java·开发语言·数据结构·python
前端摸鱼匠15 小时前
YOLOv8 环境配置全攻略:Python、PyTorch 与 CUDA 的和谐共生
人工智能·pytorch·python·yolo·目标检测
WangYaolove131415 小时前
基于python的在线水果销售系统(源码+文档)
python·mysql·django·毕业设计·源码
AALoveTouch15 小时前
大麦网协议分析
javascript·python
ZH154558913116 小时前
Flutter for OpenHarmony Python学习助手实战:自动化脚本开发的实现
python·学习·flutter
xcLeigh16 小时前
Python入门:Python3 requests模块全面学习教程
开发语言·python·学习·模块·python3·requests
xcLeigh16 小时前
Python入门:Python3 statistics模块全面学习教程
开发语言·python·学习·模块·python3·statistics