lhl
首页
python
leetcode
产品思想
软件测试
博客 (opens new window)
github (opens new window)
首页
python
leetcode
产品思想
软件测试
博客 (opens new window)
github (opens new window)
  • python

  • leetcode

    • 数组

    • 位运算

    • 动态规划

    • 链表

      • 21. 合并两个有序链表
      • 141. 环形链表
      • 142. 环形链表 II
      • 160. 相交链表
      • 203. 移除链表元素
      • 206. 反转链表
      • 234.回文链表
    • 栈

    • 树

  • 软件测试

  • Git

  • linux

  • 产品

  • MySql

  • docker

  • leetcode
  • list
2023-04-29

移除链表元素

https://leetcode.cn/problems/remove-linked-list-elements/ (opens new window)

# 迭代版本

/**
 * Definition for singly-linked list.
 * 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) {
   
    // 处理开头等于val
    while(head !== null && head.val == val){
        head = head.next
    }
       
    // 如果head 为空,返回 head
    if(head === null)
        return head

    // 如果 head 不为空,则继续遍历 head
    let prev = head
    while(prev.next != null){
        if(prev.next.val == val)
            prev.next = prev.next.next
        else
            prev = prev.next
    }
    
    return head

};
/**
 * Definition for singly-linked list.
 * 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) {
    
    // 虚拟头节点
    const dummyHead = new ListNode(0)
    dummyHead.next = head
    // cur指向 dummyHead
    let cur = dummyHead

    // 遍历的是 cur.next
    while(cur.next != null){
        if(cur.next.val == val){
            // 如果 cur.next.val == val, 那么 将 cur.next 指向 cur.next.next, 遍历的还是 cur.next
            cur.next = cur.next.next
        }else{
            // 如果 不等, 那么 cur  指向 cur.next
            cur = cur.next
        }
    }
    return dummyHead.next
};

# 递归

var removeElements = function(head, val) {
    // 递归解法
    // 如果head 为空, 直接返回
    if( head == null)
        return head
    // 递归解法关注的是头节点的结果和剩下节点的结果
    // 在这里我不会直接求解剩下节点的结果
    // result 是剩下节点的结果, 暂时放入递归函数
    let result = removeElements(head.next, val)
    if(head.val == val)
    // 头节点的值等于 val 那么删除该节点
        return result
    else{
    // 头节点的值!= val, 那么返回结果是 head+ result
        head.next = result
        return head
    }
};
160. 相交链表
206. 反转链表

← 160. 相交链表 206. 反转链表→

最近更新
01
lhl learn notes
02
filter
06-09
03
decorator
06-09
更多文章>
Theme by Vdoing
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式