Golang Leetcode 203. Remove Linked List Elements.go

版权声明:原创勿转 https://blog.csdn.net/anakinsun/article/details/89012730

思路

用一个指针负责跟踪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

猜你喜欢

转载自blog.csdn.net/anakinsun/article/details/89012730
今日推荐