Solution


  • 0
    S

    My solution

    class Solution {
        public ListNode removeElements(ListNode head, int val) {
            if(head==null) return null;
            if(head.val==val && head.next == null)return null;
            ListNode p = head;
            
            
            while(p.next != null) {
                if(p.next.val == val) {
                    p.next = p.next.next;
                } else {
                    p = p.next;
                }
            }
            
            // remove n'th first elements that equal to val
            while(head != null && head.val == val) {
                head = head.next;
            }
            
            return head;
        }
    }
    

Log in to reply
 

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