c# solution O(n)


  • 0
    N
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     public int val;
     *     public ListNode next;
     *     public ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode RemoveElements(ListNode head, int val) {
            
            var current = head;
            if(current == null) //if head is null then linked list is empty, simply return in this case
            {
                return current;
            }
            
            //edge case where head has value equal to input param val
            while(head!=null && head.val == val)
            {
                var temp = head.next;
                head = temp;
            }
            
            while(current.next != null) //loop till the end of the list
            {
                if(current.next.val == val)
                {
                    current.next = current.next.next;                
                }
                else
                {
                    current = current.next;
                }
            }
            
            return head;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.