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

移除链表元素

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;  
}
相关推荐
阿让啊1 天前
C语言strtol 函数使用方法
c语言·数据结构·c++·单片机·嵌入式硬件
superlls1 天前
(算法 哈希表)【LeetCode 349】两个数组的交集 思路笔记自留
java·数据结构·算法
Ripple123121 天前
数据结构:顺序表与链表
数据结构·链表
一个响当当的名号1 天前
B树,B+树,B*树(无代码)
数据结构·b树
古译汉书1 天前
嵌入式铁头山羊stm32-ADC实现定时器触发的注入序列的单通道转换-Day26
开发语言·数据结构·stm32·单片机·嵌入式硬件·算法
野犬寒鸦1 天前
力扣hot100:相交链表与反转链表详细思路讲解(160,206)
java·数据结构·后端·算法·leetcode
GalaxyPokemon1 天前
LeetCode - 1089. 复写零
数据结构
失散131 天前
分布式专题——1.2 Redis7核心数据结构
java·数据结构·redis·分布式·架构
zzzsde1 天前
【数据结构】强化训练:从基础到入门到进阶(1)
数据结构
奔跑吧 android1 天前
【linux kernel 常用数据结构和设计模式】【数据结构 3】【模拟input子系统input_dev和input_handler之间的多对多关系】
linux·数据结构·input·kernel·input_dev·input_handler·input_handle