Recursion-Linked Lists

Remove Linked List

Estimated reading: 1 minute 43 views

Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.

 

 

Input: head = [1,2,6,3,4,5,6], val = 6

Output: [1,2,3,4,5]

				
					public ListNode removeElements(ListNode head, int val) {
    if (head == null) {
        return null;
    }
    if (head.val == val) {
        return removeElements(head.next, val);
    }
    head.next = removeElements(head.next, val);
    return head;
}

				
			
Share this Doc

Remove Linked List

Or copy link

CONTENTS