力扣刷题:定义链表 2023.6.26

定义

class MyLinkedList(object) 这个类,开始我以为是既要定义链表,又要在该类里写方法。但其实ListNode类是在外面定义的。如下:

class ListNode:
    def __init__(self, nums = 0, next = None): # 记得要给初值
        self.nums = nums
        self.next = next

相当于, MyLinkedList(object) 这个类,是用来实现一系列list操作的。并没有规定链表的构造。

但是,我们在创建一个链表 myList 时,我们用的是:MyLinkedList myList = new MyLinkedList ,而不是直接创建一个单独的 ListNode 。至于给链表赋值啥的,用的都是 MyLinkedList 里的方法。

代码

class ListNode:
    def __init__(self, nums=0, next=None):
        self.nums = nums
        self.next = next


class MyLinkedList(object):
    def __init__(self):
        self.dummy_head = ListNode()
        self.size = 0

    def get(self, index):
        # 安全性检查
        if index < 0 or index > self.size - 1:
            return -1

        cur = self.dummy_head
        for i in range(0, index + 1):
            cur = cur.next
        return cur.nums

    def addAtHead(self, val):
        self.size += 1
        self.dummy_head.next = ListNode(val, self.dummy_head.next)

    def addAtTail(self, val):
        self.size += 1
        cur = self.dummy_head
        while cur.next:
            cur = cur.next
        cur.next = ListNode(val, None)

    def addAtIndex(self, index, val):
        if index < 0 or index > self.size:
            return -1

        self.size += 1
        new_node = ListNode(val, None)
        cur = self.dummy_head
        for i in range(0, index):
            cur = cur.next
        new_node.next = cur.next
        cur.next = new_node

    def deleteAtIndex(self, index):
        if index < 0 or index >= self.size:
            return -1

        self.size -= 1
        cur = self.dummy_head
        for i in range(0, index):
            cur = cur.next
        cur.next = cur.next.next

问题

  1. 一定要做安全性检查,否则当索引超出规定时,会报错。
  2. 与索引有关的需求时,都会用到 dummy_head
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值