Delete Even-Valued Nodes From a Linked List
Updated
Problem statement
You are given head, the first node of a singly linked list. Each node holds an integer val and a pointer next to the next node.
Delete every node whose value is even, and return the head of the list that is left. A value is even when it can be divided by 2 with no remainder, so 0 and negative values such as -4 are even, while -3 is odd.
The nodes that stay must keep their original order. If the list is empty, or every node is deleted, return null. The returned list is shown as an array of its values, with [] for an empty list.
Function
deleteEvenNodes(head: ListNode) → ListNodeExamples
Example 1
head = [5,2,9,4,4,1]return = [5,9,1]The list is 5 -> 2 -> 9 -> 4 -> 4 -> 1. The values 2, 4 and 4 are even, so those three nodes are deleted. The two 4 nodes sit next to each other, and both go.
The odd values 5, 9 and 1 stay in their order: 5 -> 9 -> 1.
Example 2
head = [6,-3,0,-8,7]return = [-3,7]The head holds 6, which is even, so it is deleted and the node -3 becomes the new head. 0 is even, because 0 = 2 × 0. -8 is even too, because -8 = 2 × (-4). -3 and 7 are odd, so the answer is -3 -> 7.
Example 3
head = [2,4,6]return = []All three values are even, so every node is deleted. Nothing is left, so the function returns null, shown as [].
Constraints
- The number of nodes in the list is between
0and1000. -10^5 <= Node.val <= 10^5