代码随想录第三天 链表

第一题 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/

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

相关推荐
y1su1 小时前
Leetcode 二分模板
java·数据结构·算法·leetcode·排序算法
bksczm1 小时前
数据结构的大纲概括
数据结构
千千寰宇2 小时前
[数据库系统] 数据库系统的设计原理研究
数据结构·数据库·database-opengemini/influxdb·database-dament/达梦
殷色玫瑰3 小时前
C++ STL:map 与 set 详解——从底层红黑树到实际应用
c语言·数据结构·c++·算法·visualstudio·rpc
字节跳动的猫3 小时前
LikeShop 商品评价体系二开:追评、晒图审核与评价标签筛选功能开发
运维·数据结构·数据库
All for pursuit.4 小时前
【动态规划-8】152.乘积最大子数组
数据结构·c++·算法·leetcode·动态规划
信奥卷王4 小时前
[GESP202512 六级] 路径覆盖
数据结构·算法
INGNIGHT5 小时前
1861 · 老鼠跳跃(坐标型dp)
数据结构·c++
0+1115 小时前
算法 --归并排序
数据结构·算法·排序算法
字节跳动的猫5 小时前
LikeShop 种草社区模块二开:笔记发布、话题广场与商品挂载实现
数据结构·数据库