leetcode707---设计链表

leetcode707—设计链表

关键词:定义链表的结构和方法

设计链表的实现。您可以选择使用单链表或双链表。单链表中的节点应该具有两个属性:val 和 next。val 是当前节点的值,next 是指向下一个节点的指针/引用。如果要使用双向链表,则还需要一个属性 prev 以指示链表中的上一个节点。假设链表中的所有节点都是 0-index 的。

在链表类中实现这些功能:

  • get(index):获取链表中第 index 个节点的值。如果索引无效,则返回-1。
  • addAtHead(val):在链表的第一个元素之前添加一个值为 val 的节点。插入后,新节点将成为链表的第一个节点。
  • addAtTail(val):将值为 val 的节点追加到链表的最后一个元素。
  • addAtIndex(index,val):在链表中的第 index 个节点之前添加值为 val 的节点。如果 index等于链表的长度,则该节点将附加到链表的末尾。如果 index 大于链表长度,则不会插入节点。如果index小于0,则在头部插入节点。
  • deleteAtIndex(index):如果索引 index 有效,则删除链表中的第 index 个节点。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/design-linked-list


解法

要点:

  • 定义一个结点类,实现结点的结构
  • 通过在链表类中利用虚拟头结点来简化处理,并统计结点数量方便判断输入index是否合法
  • 确定各种遍历操作的起始位置,方便处理循环条件
  • 类似的操作总结起来只写一次(题目要求的三种添加结点在一个函数中实现,不需要写三次)

练习了链表基础的操作。

1. 单链表

完整代码:

# 定义结点类
class ListNode():
    def __init__(self, val):
        self.val = val
        self.next = None

# 链表类
class MyLinkedList:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        # 虚拟头结点,方便处理
        self.head = ListNode(0)
        self.count = 0

    # 获取某个index对应的值
    def get(self, index: int) -> int:
        """
        Get the value of the index-th node in the linked list. If the index is invalid, return -1.
        """
        # 不合法返回-1
        if index > self.count-1 or index < 0:
            return -1
        node = self.head.next
        # 合法进行遍历
        for i in range(index):
            node = node.next
        return node.val

    # 头部添加结点
    def addAtHead(self, val: int) -> None:
        """
        Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
        """
        self.addAtIndex(0, val)

    # 尾部添加结点
    def addAtTail(self, val: int) -> None:
        """
        Append a node of value val to the last element of the linked list.
        """
        self.addAtIndex(self.count, val)

    # 对应位置处添加结点
    def addAtIndex(self, index: int, val: int) -> None:
        """
        Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted.
        """
        #  index小于0改为0
        if index < 0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值