diff --git a/datastructure/link/singlylink.go b/datastructure/link/singlylink.go index e189495..bb58f24 100644 --- a/datastructure/link/singlylink.go +++ b/datastructure/link/singlylink.go @@ -3,6 +3,7 @@ package datastructure import ( "errors" "fmt" + "reflect" "github.com/duke-git/lancet/v2/datastructure" ) @@ -144,6 +145,27 @@ func (link *SinglyLink[T]) DeleteAt(index int) error { return errors.New("delete error") } +// DeleteValue delete value in singly linklist +func (link *SinglyLink[T]) DeleteValue(value T) { + if link.Head == nil { + return + } + dummyHead := datastructure.NewLinkNode(value) + dummyHead.Next = link.Head + current := dummyHead + + for current.Next != nil { + if reflect.DeepEqual(current.Next.Value, value) { + current.Next = current.Next.Next + link.length-- + } else { + current = current.Next + } + } + + link.Head = dummyHead.Next +} + // Reverse the linked list func (link *SinglyLink[T]) Reverse() { var pre, next *datastructure.LinkNode[T] diff --git a/datastructure/link/singlylink_test.go b/datastructure/link/singlylink_test.go index 0bacc3e..c2cbee4 100644 --- a/datastructure/link/singlylink_test.go +++ b/datastructure/link/singlylink_test.go @@ -111,6 +111,24 @@ func TestSinglyLink_DeleteAtTail(t *testing.T) { assert.Equal(expected, values) } +func TestSinglyLink_DeleteValue(t *testing.T) { + assert := internal.NewAssert(t, "TestSinglyLink_DeleteValue") + + link := NewSinglyLink[int]() + + link.InsertAtTail(1) + link.InsertAtTail(2) + link.InsertAtTail(2) + link.InsertAtTail(3) + link.InsertAtTail(4) + + link.DeleteValue(2) + assert.Equal([]int{1, 3, 4}, link.Values()) + + link.DeleteValue(1) + assert.Equal([]int{3, 4}, link.Values()) +} + func TestSinglyLink_DeleteAt(t *testing.T) { assert := internal.NewAssert(t, "TestSinglyLink_DeleteAt")