leetcode 203.移除链表元素

leetcode 203.移除链表元素

大家好,我是小学五年级在读的蒟蒻,专注于后端,一起见证蒟蒻的成长,您的评论与赞与关注是我的最大动力,如有错误还请不吝赐教,万分感谢。一起支持原创吧!纯手打有笔误还望谅解。

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

题解

遍历节点,如果当前节点的下一个节点的元素是要删除的元素则将当前节点的指针指向下个节点的指针指向

/*
 * @lc app=leetcode.cn id=203 lang=cpp
 *
 * [203] 移除链表元素
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution
{
public:
    ListNode *removeElements(ListNode *head, int val)
    {
        //删除头节点的元素
        while (head != NULL && head->val == val)
        {
            ListNode *temp = head;
            head = head->next;
            delete temp;
        }
        //删除非头节点的部分
        ListNode *index = head;
        while (index != NULL && index->next != NULL)
        {
            if (index->next->val == val)
            {
                ListNode *temp = index->next;
                index->next = temp->next;
                delete temp;
            }
            else
            {
                index = index->next;
            }
        }
        return head;
    }
};
// @lc code=end


题解二

使用虚头节点来遍历链表

在头节点之前再添加一个节点,以添加的节点作为头节点遍历

/*
 * @lc app=leetcode.cn id=203 lang=cpp
 *
 * [203] 移除链表元素
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution
{
public:
    ListNode *removeElements(ListNode *head, int val)
    {
        //虚头节点
        ListNode *vir = new ListNode(0);
        vir->next = head;
        ListNode *index = vir;
        //遍历链表
        while (index->next != NULL)
        {
            //如果遇到删除的元素则移动元素
            if (index->next->val == val)
            {
                ListNode *temp = index->next;
                index->next = temp->next;
                delete temp;
            }
            else
            {
                index = index->next;
            }
        }
        head = vir->next;
        return head;
    }
};
// @lc code=end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小学五年级在读的蒟蒻

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值