代码随想录第三天 链表

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

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

相关推荐
wuyk5554 小时前
3.链表:用指针串联的动态数据结构
c语言·开发语言·数据结构·链表
郝学胜-神的一滴5 小时前
干货版《算法导论》17:二叉树核心原理、遍历逻辑与高阶实操全解
数据结构·c++·python·算法·计算机·编程
疯狂打码的少年5 小时前
【数据结构】二叉树的性质(五大性质+计算)
数据结构·笔记·算法
wabs6666 小时前
关于图论【A*算法 | 卡码网127.骑士的攻击的思考】
数据结构·算法·图论·卡码网·广搜的改进版
凉茶钱6 小时前
【数据结构】堆的应用
c语言·数据结构
间歇性努力持续性发呆的野生快乐选手7 小时前
栈的性质(进栈,出栈,访问)
数据结构·c++
m0_547486668 小时前
《数据结构与算法》全套PPT课件2026(中国海洋大学)
数据结构·算法
旖旎夜光8 小时前
LeetCode 904:水果成篮(滑动窗口) —— 题解
数据结构·c++·算法·leetcode·滑动窗口
我变成萤火虫10 小时前
河南萌新联赛2026第(三)场:郑州轻工业大学
数据结构·c++·算法·贪心算法·stl·深度优先·哈希算法
白狐_79810 小时前
408数据结构第7章:B树①——基础概念与结构
数据结构·b树