GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — 删除链表的节点-面试题18 · Issue #40 · sl1673495/leetcode-javascript

删除链表的节点-面试题18 #40

New issue
Copy link
New issue
Copy link
Open
Open
删除链表的节点-面试题18#40
Copy link
Labels
链表

Description

@sl1673495
sl1673495
opened on May 23, 2020
Issue body actions

面试题 18.删除链表的节点
给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。

返回删除后的链表的头节点。

注意:此题对比原题有改动

示例 1:

输入: head = [4,5,1,9], val = 5
输出: [4,1,9]
解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
示例 2:

输入: head = [4,5,1,9], val = 1
输出: [4,5,9]
解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.

说明:

题目保证链表中节点的值互不相同
若使用 C 或 C++ 语言,你不需要 free 或 delete 被删除的节点

思路

这题循环体里的代码还是很好定义的,不断的判断 cur.next.val 是否等于目标值 val,如果等于的话,就把 cur.next 直接赋值为 cur.next.next 即可。

但是问题就在于,这个逻辑对于头部节点是不适用的,因为是直接判断 next,所以这种题目有个通用的思路就是建立一个虚拟节点 virtual node 来替换头部位置,这样就可以轻松解决此题。

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} val
 * @return {ListNode}
 */
var deleteNode = function (head, val) {
  let virtual = {
    next: head,
  }
  let cur = virtual
  while (cur) {
    if (cur.next) {
      if (cur.next.val === val) {
        cur.next = cur.next.next
      }
    }
    cur = cur.next
  }
  return virtual.next
}

Activity

  1. sl1673495
    added
    链表
    on May 23, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    链表

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      You are visitor 01402520 — GeezerVison does not store the pages you look up.
      Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.