diff --git a/data structures/linked list/go/linkedlistint32.go b/data structures/linked list/go/linkedlistint32.go index b3aa52f5d..b717a9c5f 100644 --- a/data structures/linked list/go/linkedlistint32.go +++ b/data structures/linked list/go/linkedlistint32.go @@ -12,6 +12,60 @@ type LinkedListInt32 struct { Last *Element } +func (ll *LinkedListInt32) DeleteByValue(value int32) { + if ll == nil { + return + } + + if ll.First.Value == value { + ll.First = ll.First.Next + return + + } + + previousToDelete := ll.First + /* + We do not want to compare the data of the node in to delete, + we are going to compare the data of the next node. + To skip the node with the input value, we need to make modifications + in the previous node next. + */ + for previousToDelete.Next.Value != value { + if previousToDelete.Next.Next == nil { + return + + } + previousToDelete = previousToDelete.Next + + } + previousToDelete.Next = previousToDelete.Next.Next + +} + +func (ll *LinkedListInt32) DeleteByIndex(value int32) { + if ll == nil { + return + } + + if value == 0 { + ll.First = ll.First.Next + return + + } + + previousNode := ll.First + var count int32 + count = 0 + + // Normal case + for count < value-1 { + count += 1 + previousNode = previousNode.Next + + } + previousNode.Next = previousNode.Next.Next +} + func (ll *LinkedListInt32) push(value int32) { newElement := Element{Value: value, Next: nil} @@ -29,9 +83,8 @@ func (ll *LinkedListInt32) push(value int32) { func print(ll LinkedListInt32) { var element = ll.First for element.Next != nil { - fmt.Printf("%v ",element.Value); + fmt.Printf("%v ", element.Value) element = element.Next } - fmt.Printf("%v ",element.Value); + fmt.Printf("%v ", element.Value) } - diff --git a/data structures/linked list/go/linkedlistint32_test.go b/data structures/linked list/go/linkedlistint32_test.go index e0245c677..7138167d1 100644 --- a/data structures/linked list/go/linkedlistint32_test.go +++ b/data structures/linked list/go/linkedlistint32_test.go @@ -1,8 +1,8 @@ package linkedlistint32 import ( - _ "testing" "testing" + _ "testing" ) func Test(t *testing.T) { @@ -28,7 +28,7 @@ func Test(t *testing.T) { t.Error("third element is not 55") } - if (ll.Last.Value != 67){ + if ll.Last.Value != 67 { t.Error("last element is not 67") } }