Skip to content

Commit 6424d5d

Browse files
committed
#203: Remove Linked List Elements; solution & tests.
1 parent 6e97403 commit 6424d5d

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/**
2+
* 203
3+
* Remove Linked List Elements
4+
**
5+
* Given the head of a linked list and an integer val,
6+
* remove all the nodes of the linked list
7+
* that has Node.val == val,
8+
* and return the new head.
9+
*
10+
* Example 1:
11+
* Input: head = [1,2,6,3,4,5,6], val = 6
12+
* Output: [1,2,3,4,5]
13+
*
14+
* Example 2:
15+
* Input: head = [], val = 1
16+
* Output: []
17+
*
18+
* Example 3:
19+
* Input: head = [7,7,7,7], val = 7
20+
* Output: []
21+
*
22+
* Constraints:
23+
* • The number of nodes in the list is in the range [0, 104].
24+
* • 1 <= Node.val <= 50
25+
* • 0 <= val <= 50
26+
**
27+
* https://leetcode.com/problems/remove-linked-list-elements/
28+
***/
29+
30+
/**
31+
* Definition for singly-linked list.
32+
* public class ListNode {
33+
* public int val;
34+
* public ListNode next;
35+
* public ListNode(int val=0, ListNode next=null) {
36+
* this.val = val;
37+
* this.next = next;
38+
* }
39+
* }
40+
***/
41+
42+
namespace Problems;
43+
44+
public class RemoveLinkedListElements
45+
{
46+
public ListNode RemoveElements( ListNode head, int val )
47+
{
48+
if ( head is null )
49+
{
50+
return head;
51+
}
52+
53+
head.next = RemoveElements( head.next, val );
54+
55+
return head.val == val ? head.next : head;
56+
}
57+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
using System.Collections;
2+
3+
using NUnit.Framework;
4+
5+
using Problems;
6+
7+
public class RemoveLinkedListElementsTests
8+
{
9+
[TestCaseSource( nameof( TestCases ) )]
10+
public ListNode RemoveElementsTest( ListNode head, int val ) =>
11+
new RemoveLinkedListElements().RemoveElements( head, val );
12+
13+
private static IEnumerable TestCases
14+
{
15+
get
16+
{
17+
yield return new TestCaseData( ListNode.Create( [1, 2, 6, 3, 4, 5, 6] ), 6 )
18+
.Returns( ListNode.Create( [1, 2, 3, 4, 5] ) );
19+
20+
yield return new TestCaseData( ListNode.Create( [] ), 1 )
21+
.Returns( ListNode.Create( [] ) );
22+
23+
yield return new TestCaseData( ListNode.Create( [7, 7, 7, 7] ), 7 )
24+
.Returns( ListNode.Create( [] ) );
25+
26+
yield return new TestCaseData( ListNode.Create( [1, 2, 2, 1] ), 2 )
27+
.Returns( ListNode.Create( [1, 1] ) );
28+
}
29+
}
30+
}

0 commit comments

Comments
 (0)