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

移除链表元素

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;  
}
相关推荐
程序员老舅30 分钟前
啃透 I2C 驱动开发,才算入门嵌入式 Linux 内核驱动
数据结构·驱动开发·b树·内核·嵌入式·嵌入式开发·i2c
lueluelue471 小时前
LeetCode:链表
算法·leetcode·链表
橘子汽水1684 小时前
Leetcode 23,543合并K个升序链表,二叉树的直径
算法·leetcode·链表
青山木8 小时前
Hot 100 --- 搜索插入位置
java·数据结构·算法·leetcode
Livia要学习11 小时前
Python2和Python3字典底层原理
数据结构
青梅橘子皮11 小时前
STL---map/set... “家族“详解(从使用到底层)(1)
数据结构·算法
Adios79412 小时前
搜索二维矩阵 II
java·数据结构·算法
灵枢时代16 小时前
小程序在生鲜配送行业,如何设计夜间预约和次日达的订单处理流程?
数据结构·人工智能·小程序
一条大祥脚16 小时前
ABC468 扫描线|贡献法|二阶差分|线段树优化DP
数据结构·算法
普通攻击往后拉1 天前
Leetcode 206. 反转链表
算法·leetcode·链表