Search code examples
godata-structureslinked-list

For loop running infinitely in go, while adding a Node to an Linked List


I am new to Golang, trying to implement some of the data structures and algo's in it,

I have written a go function that adds data to the list, but for some reason, it goes into infinite loop,I have already tried various approach to no avail, also I ended up searching for the actual code for Linked List on the internet and found various implementation, but all of them get stuck on the same place,

My Code
// linked-list.go

type Node struct {
    data int
    next *Node
}

type LinkedList struct {
    head *Node
}

func (ll *LinkedList) Add(value int) {
    node := &Node{
        data: value,
    }
    if ll.head == nil {
        ll.head = node
    }

    curr := ll.head
    for curr.next != nil {  // this is where the code gets stuck
        curr = curr.next    // this is not pointing it to the next node
    }

    curr.next = node
}
// main.go

func main() {
    ll := modules.LinkedList{}
    ll.Print()
    ll.Add(1)
    ll.Add(2)
    ll.Print()
}

Some of the codes that I tried from the internet

For ref:

golangprograms
medium blog


Solution

  • return in if condition when ll.head == nil. Currently last line of function is assigning head as head.next thus making a circular linked list which will never end.