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

题目描述

给你一个链表的头节点 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 才是新的头节点
};

相关推荐

  1. 【LeetCode】203. 元素

    2024-04-05 12:18:03       34 阅读
  2. leetcode203. 元素

    2024-04-05 12:18:03       36 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-05 12:18:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-05 12:18:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-05 12:18:03       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-05 12:18:03       20 阅读

热门阅读

  1. C#基础之类的详解

    2024-04-05 12:18:03       16 阅读
  2. Python超市商品管理系统

    2024-04-05 12:18:03       18 阅读
  3. 15、Lua 元表(Metatable)

    2024-04-05 12:18:03       16 阅读
  4. P8597 [蓝桥杯 2013 省 B] 翻硬币

    2024-04-05 12:18:03       15 阅读