Remove all elements from a linked list matching given value

0

How to Remove all elements from a linked list of integers that have value val. ?

Example:

Input: 1->2->6->3->4->5->6, val = 6 
Output: 1->2->3->4->5
Edited question
0
Datsfreak (anonymous) 0 Comments

Below is a JavaScript algorithm.

We handle edge cases first:-

 

  • Delete first element if there is a match
  • Delete all the matching elements in between
  • Delete last element if there is a match

 

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
  /**
 * @param {ListNode} head
 * @param {number} val
 * @return {ListNode}
 */
var removeElements = function(head, val) {
 var prevNode = currNode,
  currNode = head;
      // remove first node if matches
    if (currNode && currNode.val === val)
 head = currNode.next;
  while (currNode) {
  prevNode = currNode;
  currNode = currNode.next;
   if (currNode && currNode.val === val) {
   prevNode.next = currNode.next;
            currNode = prevNode;
  }
 }
      // remove last node if matches
 while (head && head.val === val)
 head = head.next;
  return head;
};

Changed status to publish
Write your answer.

Categories