diff --git a/problems/remove-duplicates-from-sorted-list/remove_duplicates_from_sorted_list.go b/problems/remove-duplicates-from-sorted-list/remove_duplicates_from_sorted_list.go index f0c212b97..e6046cd59 100644 --- a/problems/remove-duplicates-from-sorted-list/remove_duplicates_from_sorted_list.go +++ b/problems/remove-duplicates-from-sorted-list/remove_duplicates_from_sorted_list.go @@ -1 +1,21 @@ package remove_duplicates_from_sorted_list + +import . "github.com/openset/leetcode/internal/kit" + +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func deleteDuplicates(head *ListNode) *ListNode { + for prev, t := head, head; t != nil; t = t.Next { + if prev.Val == t.Val { + prev.Next = t.Next + } else { + prev = t + } + } + return head +} diff --git a/problems/remove-duplicates-from-sorted-list/remove_duplicates_from_sorted_list_test.go b/problems/remove-duplicates-from-sorted-list/remove_duplicates_from_sorted_list_test.go index f0c212b97..d3a5fe88d 100644 --- a/problems/remove-duplicates-from-sorted-list/remove_duplicates_from_sorted_list_test.go +++ b/problems/remove-duplicates-from-sorted-list/remove_duplicates_from_sorted_list_test.go @@ -1 +1,36 @@ package remove_duplicates_from_sorted_list + +import ( + "reflect" + "testing" + + . "github.com/openset/leetcode/internal/kit" +) + +type caseType struct { + input []int + expected []int +} + +func TestDeleteDuplicates(t *testing.T) { + tests := [...]caseType{ + { + input: []int{1, 1, 2}, + expected: []int{1, 2}, + }, + { + input: []int{1, 1, 2, 3, 3}, + expected: []int{1, 2, 3}, + }, + { + input: []int{0, 0, 1, 1, 2, 2}, + expected: []int{0, 1, 2}, + }, + } + for _, tc := range tests { + output := deleteDuplicates(SliceInt2ListNode(tc.input)) + if !reflect.DeepEqual(ListNode2SliceInt(output), tc.expected) { + t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected) + } + } +}