【数据结构与算法】力扣 203. 移除链表元素

文章介绍了如何遍历链表并删除所有值等于给定值的节点,使用while循环和条件判断,同时讨论了特殊情况如头节点和所有节点值都相同的处理方式。
摘要由CSDN通过智能技术生成

题目描述

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

示例 1:

输入: head = [1,2,6,3,4,5,6], val = 6
输出: [1,2,3,4,5]

示例 2:

输入: head = [], val = 1
输出: []

示例 3:

输入: head = [7,7,7,7], val = 7
输出: []

提示:

  • 列表中的节点数目在范围 [0, 104] 内
  • 1 <= Node.val <= 50
  • 0 <= val <= 50

分析解答

我们做题的思路一般来说都是从简到难,从特殊到一般。

所以要删除一样的节点,那就是 if(head.val == val);head = head.next; 。那如果新的头节点的 val 还是一样的捏?好吧,将 if 改为 while。头节点暂时计算处理完成了。

接下来处理其他节点,用 temp 接收一下 head,不断 while 处理一般情况。既然接收的是 head,要就要从 temp.next 开始判断了。temp.next.val == val的话就去除temp.next = temp.next.next,否则就直接temp = temp.next下一个。

然后返回 head 就算完成最主要部分了。

最后解决遗留问题。

  • 如果head 是null,那么直接return null
  • 如果 head 都和 val 相同,那么 找到最后 head.next == null 的时候return null
  • 非 head 的情况,当temp.next == null 的时候,跳出 while

至此,做完~

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
function ListNode(val, next) {
    this.val = (val === undefined ? 0 : val)
    this.next = (next === undefined ? null : next)
}

/**
 * @param {ListNode} head
 * @param {number} val
 * @return {ListNode}
 */
var removeElements = function (head, val) {
    if (head == null) return null
    while (head.val == val) {
        if (head.next != null) {
            head = head.next;
        } else {
            return null
        }
    }
    let temp = head
    while (true) {
        if (temp.next == null) {
            break
        }
        if (temp.next.val == val) {
            temp.next = temp.next.next;
        } else {
            temp = temp.next;
        }
    }
    return head
};

思路拓展

参考:「代码随想录」 的题解

删除节点:

  • 头节点:

image.png

  • 普通节点:

image.png

其他方法:虚拟头节点

image.png

/**
 * @param {ListNode} head
 * @param {number} val
 * @return {ListNode}
 */
var removeElements = function(head, val) {
    const ret = new ListNode(0, head);
    let cur = ret;
    while(cur.next) {
        if(cur.next.val === val) {
            cur.next =  cur.next.next;
            continue;
        }
        cur = cur.next;
    }
    return ret.next;  // head 可能已经被删掉了,ret.next 才是新的头节点
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

秀秀_heo

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

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

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

打赏作者

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

抵扣说明:

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

余额充值