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;
}
相关推荐
m0_547486661 天前
《数据结构教程》全套 PPT课件2026
数据结构
tryxr2 天前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_32 天前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
All for pursuit.2 天前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
All for pursuit.2 天前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
渡我白衣2 天前
HttpRequest与HttpResponse的实现
服务器·数据结构·c++·人工智能·tcp/ip·机器学习·caffe
晴天的雨.9922 天前
【C++算法】和为s的两个数
开发语言·数据结构·c++·算法
无敌贵点大王2 天前
RTThread学习记录11——RT-Thread 设备模型吃透:UART/ADC/PWM/PIN 到底有什么区别?
c语言·stm32·学习·链表
淡海水2 天前
13-04-面试-源码级深度追问链
数据结构·unity·面试·c#·游戏引擎·源码·il2cpp
Logic1012 天前
C语言/数据结构位运算题解:异或XOR找出时尚聚会中的“独特颜色“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质