LeetCode: Remove Linked List Elements Solution
Keep next nextApproach
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} head10 * @param {number} val11 * @return {ListNode}12 */13var removeElements = function (head, val) {14 while (head && head.val === val) {15 head = head.next16 }1718 let iter = head19 while (iter && iter.next) {20 while (iter.next && iter.next.val === val) {21 iter.next = iter.next.next22 }23 iter = iter.next24 }2526 return head27}
Implementation (recursive)
1var removeElements = function (node, val) {2 if (!node) return null3 // 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 : node7}
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
2 pointers running simultaneously
Previous Post
LeetCode: Reverse Linked List
Update head each iteration