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

移除链表元素

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;  
}
相关推荐
多米Domi0111 天前
0x3f第33天复习 (16;45-18:00)
数据结构·python·算法·leetcode·链表
曹仙逸1 天前
数据结构day04
数据结构
Lips6111 天前
2026.1.16力扣刷题
数据结构·算法·leetcode
曹仙逸1 天前
数据结构day05
数据结构
睡一觉就好了。1 天前
树的基本结构
数据结构
kaikaile19951 天前
A星算法避开障碍物寻找最优路径(MATLAB实现)
数据结构·算法·matlab
今天_也很困1 天前
LeetCode 热题100-15.三数之和
数据结构·算法·leetcode
思成Codes1 天前
ACM训练:接雨水3.0——动态接雨水
数据结构·算法
sin_hielo1 天前
leetcode 2943
数据结构·算法·leetcode
Snow_day.1 天前
有关平衡树
数据结构·算法·贪心算法·动态规划·图论