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)
相关推荐
wuqingshun31415922 分钟前
蓝桥杯 2. 确定字符串是否是另一个的排列
数据结构·c++·算法·职场和发展·蓝桥杯
hu_yuchen1 小时前
C++:BST、AVL、红黑树
开发语言·c++
炯哈哈1 小时前
【上位机——MFC】视图
开发语言·c++·mfc·上位机
我也不曾来过11 小时前
继承(c++版 非常详细版)
开发语言·c++
长沙火山1 小时前
9.ArkUI List的介绍和使用
数据结构·windows·list
1白天的黑夜12 小时前
贪心算法-2208.将数组和减半的最小操作数-力扣(LeetCode)
c++·算法·leetcode·贪心算法
AAAA劝导tx2 小时前
List--链表
数据结构·c++·笔记·链表·list
格格Code2 小时前
八大排序——冒泡排序/归并排序
数据结构·算法·排序算法
愚润求学3 小时前
【Linux】进程优先级和进程切换
linux·运维·服务器·c++·笔记
Dream it possible!3 小时前
LeetCode 热题 100_最小路径和(92_64_中等_C++)(多维动态规划)
c++·leetcode·动态规划