Remove Linked List Elements

Solution in Go

func removeElements(head *ListNode, val int) *ListNode {
    var (
        prev *ListNode = nil
        curr *ListNode = head
    )

    for curr != nil {
        if curr.Val == val {
            // Head node
            if prev == nil {
                head = head.Next
                curr = head
            } else {
                prev.Next = curr.Next
                curr = curr.Next
            }
            continue
        }
        prev = curr
        curr = curr.Next
    }

    return head
}
Subscribe via email

Get notified once/twice per month when new articles are published.

Copyright © 2022 - 2024 TheDeveloperCafe.
The Go gopher was designed by Renee French.