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
相关推荐
天雪浪子8 分钟前
Python入门教程之逻辑运算符
开发语言·python
张子夜 iiii33 分钟前
实战项目-----在图片 hua.png 中,用红色画出花的外部轮廓,用绿色画出其简化轮廓(ε=周长×0.005),并在同一窗口显示
人工智能·pytorch·python·opencv·计算机视觉
gongzemin37 分钟前
Django入门2--设置数据库 admin
python·django
KimLiu1 小时前
LCODER之Python:使用Django搭建服务端
后端·python·django
胡耀超1 小时前
3.Python高级数据结构与文本处理
服务器·数据结构·人工智能·windows·python·大模型
云:鸢1 小时前
C语言链表设计及应用
c语言·开发语言·数据结构·链表
1373i1 小时前
【Python】pytorch安装(使用conda)
pytorch·python·conda
keyinf01 小时前
python网络爬取个人学习指南-(五)
python