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;
}
相关推荐
大数据追光猿1 小时前
Python应用算法之贪心算法理解和实践
大数据·开发语言·人工智能·python·深度学习·算法·贪心算法
Dream it possible!2 小时前
LeetCode 热题 100_在排序数组中查找元素的第一个和最后一个位置(65_34_中等_C++)(二分查找)(一次二分查找+挨个搜索;两次二分查找)
c++·算法·leetcode
夏末秋也凉2 小时前
力扣-回溯-46 全排列
数据结构·算法·leetcode
南宫生2 小时前
力扣每日一题【算法学习day.132】
java·学习·算法·leetcode
柠石榴2 小时前
【练习】【回溯No.1】力扣 77. 组合
c++·算法·leetcode·回溯
Leuanghing2 小时前
【Leetcode】11. 盛最多水的容器
python·算法·leetcode
qy发大财2 小时前
加油站(力扣134)
算法·leetcode·职场和发展
王老师青少年编程2 小时前
【GESP C++八级考试考点详细解读】
数据结构·c++·算法·gesp·csp·信奥赛
qy发大财2 小时前
柠檬水找零(力扣860)
算法·leetcode·职场和发展
瓦力的狗腿子2 小时前
Starlink卫星动力学系统仿真建模番外篇6-地球敏感器
算法·数学建模·simulink