代码随想录第三天 链表

第一题 https://leetcode.cn/problems/remove-linked-list-elements/submissions/691848826/

python 复制代码
# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


from typing import Optional


class Solution:
    def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
        dummy = ListNode(0, head)
        cur = dummy

        while cur.next:
            if cur.next.val == val:
                cur.next = cur.next.next
            else:
                cur = cur.next

        return dummy.next

注意cur.next为待删除目标时cur不往后移,因为后面还可能是相同元素。虚拟头结点还是挺方便的。

第二题 反转链表https://leetcode.cn/problems/reverse-linked-list/description/

python 复制代码
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        cur = head
        pre = None
        while cur:
            next = cur.next
            cur.next = pre
            pre = cur
            cur = next
        return pre

代码不难,也用不着虚拟头结点。

第三题 https://leetcode.cn/problems/design-linked-list/description/

设计类的还是有点难度的,注意索引是否越界要提前判断,首尾插入都应该是按索引插入的特例

相关推荐
Mr. zhihao5 小时前
深入解析redis基本数据结构
数据结构·数据库·redis
念何架构之路6 小时前
Go语言加密算法
数据结构·算法·哈希算法
失去的青春---夕阳下的奔跑6 小时前
560. 和为 K 的子数组
数据结构·算法·leetcode
m0_629494737 小时前
LeetCode 热题 100-----25.回文链表
数据结构·算法·leetcode·链表
吃着火锅x唱着歌9 小时前
LeetCode 1019.链表中的下一个更大节点
算法·leetcode·链表
青山师10 小时前
二叉树与BST深度解析:遍历算法与平衡策略
数据结构·算法·面试·二叉树·算法与数据结构·java面试·数据结构与算法分析
宇明一不急10 小时前
go 链表 (标准库实现)
开发语言·链表·golang
无限进步_13 小时前
【C++】C++11的类功能增强与STL变化
java·前端·数据结构·c++·后端·算法
sa1002714 小时前
京东评论 API 实战:JSON 数据结构、字段含义与解析技巧
前端·数据结构·json