# 删除链表的节点(剑指Offer 18)

# 题目

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

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

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

# 示例

输入: head = [4,5,1,9], val = 5 输出: [4,1,9]

输入: head = [4,5,1,9], val = 1 输出: [4,5,9]

# 说明

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

# 算法

# 原地删除

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
export const deleteNode = (head, val) => {
	if (head.val === val) return head.next;
	let node = head;
	while (node.next) {
		if (node.next.val === val) {
			node.next = node.next.next;
			return head;
		}
		node = node.next;
	}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# 递归

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
export const deleteNode = (head, val) => {
	if (head.val === val) return head.next;
	head.next = deleteNode(head.next, val);
	return head;
};
1
2
3
4
5
6
7
8
9
10
11
12