LeetCode: Remove Linked List Elements Solution

Keep next next

Approach

Keep skipping element by next

For iterative solution, do that first for

head
to maintain valid
head
's
val

Implementation (iterative)

1/**
2 * Definition for singly-linked list.
3 * function ListNode(val, next) {
4 * this.val = (val===undefined ? 0 : val)
5 * this.next = (next===undefined ? null : next)
6 * }
7 */
8/**
9 * @param {ListNode} head
10 * @param {number} val
11 * @return {ListNode}
12 */
13var removeElements = function (head, val) {
14 while (head && head.val === val) {
15 head = head.next
16 }
17
18 let iter = head
19 while (iter && iter.next) {
20 while (iter.next && iter.next.val === val) {
21 iter.next = iter.next.next
22 }
23 iter = iter.next
24 }
25
26 return head
27}

Implementation (recursive)

1var removeElements = function (node, val) {
2 if (!node) return null
3 // console.log('(first)', node.val, !node.next ? 'no next' : node.next.val)
4 node.next = removeElements(node.next, val)
5 // console.log('(second)', node.val, !node.next ? 'no next' : node.next.val)
6 return node.val === val ? node.next : node
7}

Comments

Loading comments...

Tags

leetcode

linked list

recursion

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Odd Even Linked List

Aug 18, 2021

2 pointers running simultaneously

Previous Post

LeetCode: Reverse Linked List

Aug 15, 2021

Update head each iteration

HoningJS

Search Posts