Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f6d0ae3

Browse files
authored
recursive solution for 203 (keep-practicing#69)
1 parent b95f9e9 commit f6d0ae3

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

‎src/0203_remove_linked_list_elements/remove_linked_list_elements.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,17 @@ func removeElements(head *ListNode, val int) *ListNode {
3131
}
3232
return dummyHead.Next
3333
}
34+
35+
// recursive
36+
// time complexity: O(n)
37+
// space complexity: O(n)
38+
func removeElements1(head *ListNode, val int) *ListNode {
39+
if head == nil {
40+
return head
41+
}
42+
head.Next = removeElements1(head.Next, val)
43+
if head.Val == val {
44+
return head.Next
45+
}
46+
return head
47+
}

‎src/0203_remove_linked_list_elements/remove_linked_list_elements_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,16 @@ func TestRemoveElements(t *testing.T) {
1515
}
1616
}
1717

18+
func TestRemoveElements1(t *testing.T) {
19+
head := createSinglyLinkedList([]int{1, 2, 6, 3, 4, 5, 6})
20+
val := 6
21+
expected := createSinglyLinkedList([]int{1, 2, 3, 4, 5})
22+
23+
if res := removeElements1(head, val); !reflect.DeepEqual(res, expected) {
24+
t.Errorf("expected %v, got %v", expected, res)
25+
}
26+
}
27+
1828
func createSinglyLinkedList(nums []int) *ListNode {
1929
head := &ListNode{}
2030
cur := head

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /