leetcode203.移除链表元素

目录

问题描述

给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。

题目链接:移除链表元素

示例

提示

列表中的节点数目在范围 [0, 1 0 4 10^4 104] 内

1 <= Node.val <= 50

0 <= val <= 50

具体思路

思路一

通过查找链表中节点的值不等于val,就在新的链表上进行尾插,不过这种方式实现的时间复杂度也比较高

思路二

通过遍历链表,查找链表中的值等于val就进行删除,将前一个节点(pre)的next指针指向它后一个节点,然后free掉当前节点(cur),然后再将当前节点的指针(cur)指向下一个节点

代码实现

cpp 复制代码
//思路1
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeElements(struct ListNode* head, int val) {
    struct ListNode* cur = head;
    struct ListNode* newhead=NULL;
    struct ListNode* tail=NULL;
    while(cur)
    {
        if(cur->val!=val)
        {
            if(tail==NULL)
            {
               newhead=tail=cur;
            }
            else
            {
                tail->next=cur;
                tail=tail->next;
            }
             cur=cur->next;
            tail->next=NULL; 
        }
        else
        {
            struct ListNode* del =cur;
            cur=cur->next;
            free(del);
        }
    }
    return newhead;
}
cpp 复制代码
//思路2
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeElements(struct ListNode* head, int val) {
    struct ListNode* prev =NULL;
    struct ListNode* cur = head;
    while(cur)
    {
        if(cur->val==val)
        {
            if(prev)
            {
                prev->next=cur->next;
                free(cur);
                cur =prev->next;
            }
            else
            {
                cur=head->next;
                free(head);
                head=cur;
            }
        }
        else
        {
            prev=cur;
            cur=cur->next;
        }
    }
    return head;
}
相关推荐
散峰而望30 分钟前
C++ 启程:从历史到实战,揭开命名空间的神秘面纱
c语言·开发语言·数据结构·c++·算法·github·visual studio
Darkwanderor2 小时前
数据结构 - 并查集的应用
数据结构·c++·并查集
夏乌_Wx3 小时前
LeetCode 160. 相交链表 | 三种解法吃透核心逻辑(哈希表 + 双指针 + 长度对齐)
leetcode·链表·哈希表
Hag_203 小时前
LeetCode Hot100 53.最大子数组和
数据结构·算法·leetcode
王老师青少年编程3 小时前
csp信奥赛C++之反素数
数据结构·c++·数学·算法·csp·信奥赛·反素数
元亓亓亓7 小时前
考研408--数据结构--day17--外部排序
数据结构·考研
仰泳的熊猫7 小时前
蓝桥杯算法提高VIP-种树
数据结构·c++·算法·蓝桥杯·深度优先·图论
郝学胜-神的一滴8 小时前
FastAPI:Python 高性能 Web 框架的优雅之选
开发语言·前端·数据结构·python·算法·fastapi
样例过了就是过了8 小时前
LeetCode热题100 回文链表
数据结构·算法·leetcode·链表
Solitary-walk8 小时前
前缀和思想
数据结构·c++·算法