Remove Linked List Elements
Let’s take a look at a easy problem on Leetcode 203. Remove Linked List Elements. We will demonstrate how to remove elements from a linked list.
Basically there are two ways to make it done.
a. Since all nodes in the linked list have a previous node except the head node, we can use those node’s previous node to delete those node. But if we have to remove the head node, we need to use a special logic.
1 | func removeElements(head *ListNode, val int) *ListNode { |
Golang Playbook: https://play.golang.org/p/ij55kvVD3aM
b. We can also add a virtual node to point to the head node, so all nodes including the head node have a previous node. With this change.
1 | func removeElements(head *ListNode, val int) *ListNode { |
Golang Playbook: https://play.golang.org/p/1tvSzIGDAm7