代码随想录第三天 链表

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

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

相关推荐
漂流瓶jz7 小时前
UVA-1612 猜名次 题解答案代码 算法竞赛入门经典第二版
数据结构·算法·题解·排序·aoapc·算法竞赛入门经典
A boy CDEF girl13 小时前
算法题专栏:优选算法
数据结构·算法·leetcode
图灵-M17 小时前
【数据结构】静态 & 动态顺序表
c语言·数据结构·笔记
careathers17 小时前
【数据结构】基于比较的排序算法 - 选择排序
数据结构·算法·排序算法
XiYang-DING19 小时前
P4104.环形链表判断
数据结构·链表
逆向编程19 小时前
MATLAB高级数据结构:cell、struct与table深度应用
开发语言·数据结构·matlab
m0_639906941 天前
Redis入门|五种数据结构、使用场景、持久化RDB&AOF
数据结构·数据库·redis
2601_970703831 天前
工业除湿机租赁:把一份租金合同拆开看
大数据·数据结构·算法·数据库架构·推荐算法
丘山望岳2 天前
单调栈和单调队列
数据结构
UIU1142 天前
P16237 [蓝桥杯 2026 省 B] 应急布线
数据结构·c++·算法·蓝桥杯