Leetcode算法题(移除链表中的元素)

题目如下:

思路1:创建一个新的带头链表 (newhead),遍历头结点对应的值分别于x进行比较,将不等于x的节点尾插到新的带头链表中,返回新的带头链表的下一个节点。

代码如下:

复制代码
typedef struct ListNode ListNode;
struct ListNode* removeElements(struct ListNode* head, int val) {
    ListNode* newhead, * newtail;
    newhead = newtail = (ListNode*)malloc(sizeof(ListNode));
    while (head)
    {
        if (head->val != val)
        {
            newtail->next = head;
            head = head->next;
            newtail = newtail->next;
        }
        else {
            head = head->next;
        }
    }
    newtail->next = NULL;
    return newhead->next;
}

思路2:与思路一类似,只不过是空链表,进行判断。

复制代码
typedef struct ListNode ListNode;
struct ListNode* removeElements(struct ListNode* head, int val) {
    if (head == NULL)
    {
        return NULL;
    }
    // 创建空链表
    ListNode* newhead, * newtail;
    newhead = newtail = NULL;
    while (head) {
        if (head->val != val) {
            // 空链表
            if (newhead == NULL) {
                newtail = newhead = head;
            }
            else {
                // 非空链表
                newtail->next = head;
                newtail = newtail->next;
            }
        }
        head = head->next;
    }
    if (newtail)
        newtail->next = NULL;
    return newhead;
}
相关推荐
魔云连洲30 分钟前
前端树形结构过滤算法
前端·算法
小龙报37 分钟前
《算法通关指南:数据结构和算法篇 --- 顺序表相关算法题》--- 询问学号,寄包柜,合并两个有序数组
c语言·开发语言·数据结构·c++·算法·学习方法·visual studio
小南家的青蛙2 小时前
LeetCode LCR 085 括号生成
算法·leetcode·职场和发展
jackzhuoa2 小时前
Rust 异步核心机制剖析:从 Poll 到状态机的底层演化
服务器·前端·算法
夜晚中的人海2 小时前
【C++】模拟算法习题
c++·算法·哈希算法
花月C2 小时前
算法 - 差分
人工智能·算法·机器学习
拆房老料2 小时前
深入解析提示语言模型校准:从理论算法到任务导向实践
人工智能·算法·语言模型
晨非辰2 小时前
《数据结构风云》递归算法:二叉树遍历的精髓实现
c语言·数据结构·c++·人工智能·算法·leetcode·面试
Dream it possible!2 小时前
LeetCode 面试经典 150_链表_LRU 缓存(66_146_C++_中等)(哈希表 + 双向链表)
c++·leetcode·链表·面试
_dindong5 小时前
牛客101:二叉树
数据结构·c++·笔记·学习·算法