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;
}
相关推荐
❀͜͡傀儡师2 分钟前
Spring Boot 实现图片盲水印:基于 DCT 频域算法的隐形数字水印
spring boot·算法
Zane199415 分钟前
贪心算法大多靠不住,为什么Dijkstra的贪心选择偏偏能保证全局最优
算法
CQU_JIAKE20 分钟前
9.26【A】
算法
-cywen-39 分钟前
GROUNDHOG总体版
人工智能·深度学习·算法
_不会dp不改名_42 分钟前
leetcode_1614嵌套括号的最大深度
算法·leetcode·职场和发展
sali-tec43 分钟前
C# 基于OpenCv的视觉工作流-章110-YOLO 实例分割
图像处理·人工智能·opencv·算法·yolo·计算机视觉
sunburn-1 小时前
Java 排序算法详细教学:从冒泡排序到快速排序
java·开发语言·数据结构·ide·算法
阳明山水1 小时前
因果嵌入与流水线范式的本质差异
人工智能·深度学习·算法·机器学习·架构
小静AI工程实验室1 小时前
MD5 算法详解:哈希原理、标准向量、输入编码与安全边界
算法·安全·哈希算法·md5
小许同学记录成长1 小时前
几何体编辑算法
qt·算法