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;
}
相关推荐
算法与编程之美12 分钟前
探索不同的损失函数对分类精度的影响.
人工智能·算法·机器学习·分类·数据挖掘
H_BB13 分钟前
leetcode160:相交链表
数据结构·算法·链表
前端小L43 分钟前
贪心算法专题(十五):借位与填充的智慧——「单调递增的数字」
javascript·算法·贪心算法
前端小L1 小时前
贪心算法专题(十四):万流归宗——「合并区间」
javascript·算法·贪心算法
hans汉斯1 小时前
基于数据重构与阈值自适应的信用卡欺诈不平衡分类模型研究
大数据·算法·机器学习·重构·分类·数据挖掘·机器人
ZPC82101 小时前
FANUC 机器人 PR 寄存器
人工智能·python·算法·机器人
yong99901 小时前
超宽带系统链路 MATLAB 仿真
开发语言·算法·matlab
历程里程碑2 小时前
LeetCode 560题:和为K子数组最优解
算法·哈希算法·散列表
qq_401700412 小时前
C/C++中的signed char和unsigned char详解
c语言·c++·算法
leoufung2 小时前
LeetCode 67. Add Binary:从面试思路到代码细节
算法·leetcode·面试