【数据结构】【链表代码】移除链表元素

移除链表元素

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

  
struct ListNode* removeElements(struct ListNode* head, int val) {  
    // 创建一个虚拟头节点,以处理头节点可能被删除的情况  
    struct ListNode *dummy = (struct ListNode*)malloc(sizeof(struct ListNode)); // 分配内存给 dummy 节点  
    if (dummy == NULL) {  
        return NULL; // 内存分配失败  
    }  
    dummy->val = 0;  
    dummy->next = head;  
    struct ListNode *pre = dummy;  
    struct ListNode *cur = head;  
  
    while (cur != NULL) {  
        if (cur->val == val) {  
            // 删除当前节点  
            pre->next = cur->next;  
            free(cur); // 释放当前节点的内存,因为不再需要这个节点  
            cur = pre->next; // 移动 cur 到下一个节点  
        } else {  
            // 如果不删除当前节点,则继续遍历  
            pre = cur;  
            cur = cur->next;  
        }  
    }  
  
    // 返回新的头节点(跳过虚拟头节点)  
    struct ListNode *new_head = dummy->next;  
    free(dummy); // 释放虚拟头节点的内存  
    return new_head;  
}
相关推荐
LuminousCPP9 小时前
数据结构‑二叉树(二):二叉堆从零实现|Heap结构设计 + 建堆优化 + 堆排序深度解析
c语言·数据结构·笔记·二叉树
11 小时前
数据结构第一课:复杂度解析
数据结构
欧叶冲冲冲12 小时前
Python常见数据结构的CRUD(LeetCode高频版速查)
数据结构·python·leetcode
_Narcissus_13 小时前
链表算法题和静态链表
数据结构·c++·笔记·算法·链表·ai·力扣
Lyyaoo.13 小时前
【普通数组】【中等】除了自身以外数组的乘积
数据结构·算法·leetcode
疯狂打码的少年15 小时前
【数据结构】八大排序算法对比总结(时间/空间/稳定性)
数据结构·笔记·算法
青 春 记 忆17 小时前
LeetCode 206. 反转链表|Python 解法详解
python·leetcode·链表
啊嘞嘞?19 小时前
力扣(回文链表)
算法·leetcode·链表
Awh-19 小时前
数据结构 第六章:哈希存储
数据结构·算法·哈希算法
TAN-90°-20 小时前
Deep Learning for Computer Vision——Recurrent Neural Networks
数据结构·人工智能·rnn·深度学习·神经网络·机器学习·计算机视觉