思路
用一个指针负责跟踪head的前一个节点
发现目标之后,直接跳过该节点
code
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
}
更多内容请移步我的repo: https://github.com/anakin/golang-leetcode