Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implemented DeleteByIndex and DeleteByValue in Go #1621

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
59 changes: 56 additions & 3 deletions data structures/linked list/go/linkedlistint32.go
Original file line number Diff line number Diff line change
Expand Up @@ -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}

Expand All @@ -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)
}

4 changes: 2 additions & 2 deletions data structures/linked list/go/linkedlistint32_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package linkedlistint32

import (
_ "testing"
"testing"
_ "testing"
)

func Test(t *testing.T) {
Expand All @@ -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")
}
}