LeetCode203 移除链表元素

前言

题目: 203.移除链表元素
文档: 代码随想录------移除链表元素
编程语言: C++
解题状态: 解答错误,忘了链表的遍历是如何进行的了

思路

对于链表的操作,最好可以给一个虚拟表头方便操作。另外需要注意的是,在删除链表的节点后,我们需要手动进行清理内存。

代码

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        ListNode* dummyHead = new ListNode(0); // 设置一个虚拟头结点
        dummyHead -> next = head; // 将虚拟头结点指向head,这样方便后面做删除操作
        ListNode* cur = dummyHead;
        while (cur -> next != NULL) {
            if(cur -> nex t-> val == val) {
                ListNode* tmp = cur -> next;
                cur -> next = cur -> next -> next;
                delete tmp;
            } else {
                cur = cur -> next;
            }
        }
        head = dummyHead -> next;
        delete dummyHead;
        return head;
    }
};
  • 时间复杂度: O ( n ) O(n) O(n)
  • 空间复杂度: O ( 1 ) O(1) O(1)
相关推荐
挖井观天37 分钟前
《Java数据结构》第一讲:顺序表
数据结构
努力努力再努力wz1 小时前
【C++高阶系列】C++20 协程底层原理:函数为什么能暂停?从状态机到 Task,彻底串起挂起、恢复与协程调度
开发语言·c++·c++20·1024程序员节
划破黑暗的第一缕曙光2 小时前
[C++]:4.模板
c++·template·模板·函数模版·类模版
十五年专注C++开发2 小时前
pybind11:一个跨C++和Python平台的编程库
开发语言·c++·python·pybind11
CodeYp20192 小时前
第11讲:stack 和 queue
开发语言·c++·queue·stack
炘爚2 小时前
数据结构算法总结
数据结构·python·算法
沫璃染墨2 小时前
《Qt从零入门系列(十五):Qt线程安全与锁机制详解——从QMutex到RAII与读写锁实战》
开发语言·c++·qt·安全·交互·线程·qt6.3
hetao17338372 小时前
2026-10-25 hetao1733837 的刷题记录
c++·算法
fqbqrr3 小时前
2610C++,UI复合技术在窗口中绘画字体图标
c++·ui
见叶之秋3 小时前
【C++】红与黑的边界:红黑树从插入到自检
数据结构·c++·算法·面试