# 链表中删除指定数字

删除链表中指定的数字,并返回新头部

假设,上述链表指定删除4,则返回:

# 实现

type Node struct {
	Value int
	Next *Node
}

func DeleteTargetNum(head *Node, target int) *Node {
	// 来到第一个不需要删除的位置
	for head != nil {
		if head.Value != target {
			break
		}
		head = head.Next
	}
	cur, pre := head, head
	for cur != nil {
		if cur.Value == target {
			pre.Next = cur.Next
		} else {
			pre = cur
		}
		cur = cur.Next
	}
	// 返回第一个不需要删除的位置
	return head
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
上次更新: 10/2/2023,