Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
sl1673495 opened this issue May 23, 2020 · 0 comments
Open

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

sl1673495 opened this issue May 23, 2020 · 0 comments
Labels

Comments

@sl1673495
Copy link
Owner

面试题 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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant