# LeetCode: Remove Linked List Elements Solution

Keep next next

## Approach

Keep skipping element by next

For iterative solution, do that first for

to maintain valid
's
val

## Implementation (iterative)

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}/**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  }17
18  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  }25

## 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}`

leetcode

recursion

## Next Post

Aug 18, 2021

2 pointers running simultaneously