版权声明:原创勿转 https://cloud.tencent.com/developer/article/1412910
思路
用一个指针负责跟踪head的前一个节点
发现目标之后,直接跳过该节点
code
代码语言:javascript复制func removeElements(head *ListNode, val int) *ListNode {
if head == nil {
return head
}
var p1 ListNode
p1.Next = head
p2 := &p1
for head != nil {
if head.Val == val {
p2.Next, head = head.Next, head.Next
} else {
p2, head = head, head.Next
}
}
return p1.Next
}