Skip to content

Commit

Permalink
Implemented deleteByIndex into the linked-list
Browse files Browse the repository at this point in the history
  • Loading branch information
Matheus73 committed Oct 31, 2020
1 parent 9a2f56c commit bdb5f2d
Showing 1 changed file with 48 additions and 8 deletions.
56 changes: 48 additions & 8 deletions Go/Data-Structures/linked-list/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import "fmt"

type node struct {
data int
next *node // address of the next node
next *node // address of the next node
}

// quotient list
Expand Down Expand Up @@ -43,11 +43,11 @@ func (l *linkedList) deleteWithValue(value int) {

previousToDelete := l.head
/*
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.
*/
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.data != value {
if previousToDelete.next.next == nil {
return
Expand All @@ -58,6 +58,43 @@ func (l *linkedList) deleteWithValue(value int) {
l.length--
}

func (l *linkedList) deleteByIndex(value int) {
if l.length == 0 {
return
}

if value >= l.length {
return
}

if value == 0 {
l.head = l.head.next
l.length--
return
}

previousNode := l.head
count := 0

// If i want to delete the last node
if value == l.length-1 {
for previousNode.next.next != nil {
previousNode = previousNode.next
}
previousNode.next = nil
l.length--
return
}

// Normal case
for count < value-1 {
count += 1
previousNode = previousNode.next
}
previousNode.next = previousNode.next.next
l.length--
}

func main() {
mylist := linkedList{}
node1 := &node{data: 48}
Expand All @@ -74,8 +111,11 @@ func main() {
mylist.prepend(node6)
mylist.printListData()

mylist.deleteWithValue(100)
mylist.deleteWithValue(2)
// mylist.deleteWithValue(100)
// mylist.deleteWithValue(2)
mylist.deleteByIndex(2)
mylist.printListData()
mylist.deleteByIndex(mylist.length - 1)
mylist.printListData()
emptyList := linkedList{}
emptyList.deleteWithValue(10)
Expand Down

0 comments on commit bdb5f2d

Please sign in to comment.