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;
}
相关推荐
咖啡里的茶i17 分钟前
视觉显著目标的自适应分割与动态网格生成算法研究
人工智能·算法·目标跟踪
paeamecium32 分钟前
【PAT甲级真题】- String Subtraction (20)
数据结构·c++·算法·pat考试·pat
YL2004042638 分钟前
047从前序与中序遍历序列构造二叉树
算法·leetcode
极梦网络无忧39 分钟前
password_hash
算法·哈希算法
计算机安禾1 小时前
【c++面向对象编程】第25篇:仿函数(函数对象):重载operator()
开发语言·c++·算法
周末也要写八哥2 小时前
在C++中使用预定义宏
开发语言·c++·算法
学会870上岸华师2 小时前
C 语言程序设计——第一章课后编程题
c语言·开发语言·学习·算法
小马过河R2 小时前
RAG检索优化策略:系统性四层框架解析
人工智能·python·算法·ai·llm·rag·问答
AI技术控3 小时前
论文解读:AE-TCN-SA——基于自编码器、TCN 与自注意力机制的锂电池内短路诊断方法
人工智能·python·深度学习·算法·机器学习·自然语言处理
ʚ希希ɞ ྀ3 小时前
动态规划基础知识---爬楼梯
算法·动态规划