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)
相关推荐
元亓亓亓2 小时前
LeetCode热题100--79. 单词搜索
算法·leetcode·职场和发展
FuckPatience2 小时前
C++ 常用类型写法和全称
开发语言·c++
2501_941143733 小时前
缓存中间件Redis与Memcached在高并发互联网系统优化与实践经验分享
leetcode
__BMGT()3 小时前
参考文章资源记录
开发语言·c++·qt
ouliten3 小时前
C++笔记:std::string_view
开发语言·c++·笔记
玫瑰花店3 小时前
万字C++中锁机制和内存序详解
开发语言·c++·算法
D_evil__3 小时前
[C++高频精进] 文件IO:文件流
c++
西幻凌云4 小时前
认识STL序列式容器——List
开发语言·c++·stl·list·序列式容器
靠沿4 小时前
Java数据结构初阶——LinkedList
java·开发语言·数据结构