代码随想录第三天 链表

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

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

相关推荐
BLSxiaopanlaile2 小时前
关于子集和问题的几种解法
数据结构·算法·剪枝·回溯·分解
じ☆冷颜〃3 小时前
交换代数的解析延拓及在CS的应用
c语言·数据结构·笔记·线性代数·密码学
程序员-King.3 小时前
day136—快慢指针—重排链表(LeetCode-143)
算法·leetcode·链表·快慢指针
txzrxz3 小时前
数据结构有关的题目(栈,队列,set和map)
数据结构·c++·笔记·算法··队列
CoderCodingNo3 小时前
【GESP】C++五级练习题(前缀和) luogu-P1114 “非常男女”计划
数据结构·c++·算法
我是大咖3 小时前
关于柔性数组的理解
数据结构·算法·柔性数组
wen__xvn4 小时前
代码随想录算法训练营DAY18第六章 二叉树part06
数据结构
杭州杭州杭州4 小时前
pta考试
数据结构·c++·算法
Remember_9934 小时前
【数据结构】初识 Java 集合框架:概念、价值与底层原理
java·c语言·开发语言·数据结构·c++·算法·游戏