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;
}
相关推荐
Miraitowa_cheems22 分钟前
LeetCode算法日记 - Day 64: 岛屿的最大面积、被围绕的区域
java·算法·leetcode·决策树·职场和发展·深度优先·推荐算法
Christo332 分钟前
关于K-means和FCM的凸性问题讨论
人工智能·算法·机器学习·数据挖掘·kmeans
_不会dp不改名_1 小时前
leetcode_1382 将二叉搜索树变平衡树
算法·leetcode·职场和发展
greentea_20132 小时前
Codeforces Round 173 B. Digits(2043)
c++·算法
m0_743106462 小时前
LOBE-GS:分块&致密化效率提升
人工智能·算法·计算机视觉·3d·几何学
徐子童3 小时前
优选算法---字符串
java·算法·字符串·笔试·高精度相乘
西瓜啵啵奶茶3 小时前
LeetCode 热题 100 : 普通数组
算法
jikiecui3 小时前
信奥崔老师:C++ 程序设计入门
算法
Q741_1473 小时前
C++ 位运算 高频面试考点 力扣 面试题 17.19. 消失的两个数字 题解 每日一题
c++·算法·leetcode·面试·位运算
Jacob00003 小时前
[Decision Tree] H(D) & IG & IGR
算法·面试