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)
相关推荐
小han的日常17 分钟前
pycharm分支提交操作
python·pycharm
明月清风徐徐36 分钟前
Scrapy爬取豆瓣电影Top250排行榜
python·selenium·scrapy
theLuckyLong37 分钟前
SpringBoot后端解决跨域问题
spring boot·后端·python
Yongqiang Cheng40 分钟前
Python operator.itemgetter(item) and operator.itemgetter(*items)
python·operator·itemgetter
MavenTalk43 分钟前
Move开发语言在区块链的开发与应用
开发语言·python·rust·区块链·solidity·move
FksLiao1 小时前
Superset安装
python
L Jiawen1 小时前
【Python · PyTorch】卷积神经网络(基础概念)
pytorch·python·cnn
goomind1 小时前
深度学习模型评价指标介绍
人工智能·python·深度学习·计算机视觉
->yjy1 小时前
wordcloud库基本介绍
python
2401_840192271 小时前
python基础大杂烩
linux·开发语言·python