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;
}
相关推荐
Fanxt_Ja2 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
今后1232 天前
【数据结构】二叉树的概念
数据结构·二叉树
散1123 天前
01数据结构-01背包问题
数据结构
消失的旧时光-19433 天前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww3 天前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
苏小瀚3 天前
[数据结构] 排序
数据结构
_不会dp不改名_3 天前
leetcode_21 合并两个有序链表
算法·leetcode·链表
睡不醒的kun3 天前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌3 天前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
Whisper_long3 天前
【数据结构】深入理解堆:概念、应用与实现
数据结构