0

I'm new to golang and exploring the language. I am creating a linked list, but it seems to go out of scope and does not store variables correctly.

When I print the list using this code, it prints blank, when aa, bb is expected.

package main

import "fmt"

type Node struct {
    data string
    nextNode *Node
}

type MyLinkedList struct {
    head *Node
}


func (ll MyLinkedList) pushFront(data string) *Node {
    node := Node{data, nil}
    if ll.head == nil {
        ll.head = &node
        return ll.head
    }
    node.nextNode = ll.head
    ll.head = &node
    return ll.head
}

func print(ll MyLinkedList) {
    currentNode := ll.head
    for currentNode != nil {
        fmt.Print(currentNode.data + " ")
        currentNode = currentNode.nextNode
    }
}

func main() {
    var m = MyLinkedList{}
    m.pushFront("aa")
    m.pushFront("bb")
    print(m)
}
Amigo
  • 133
  • 3
  • 5

2 Answers2

1

I modified your code to make it work.

import "fmt"

type Node struct {
    data string
    nextNode *Node
}

type MyLinkedList struct {
    head *Node
}


func (ll *MyLinkedList) pushFront(data string) {
    node := &Node{data, nil}
    if ll.head == nil {
        ll.head = node 
return
    }
    node.nextNode = ll.head
    ll.head = node 
}

func print(ll *MyLinkedList) {
    currentNode := ll.head
    for currentNode != nil {
        fmt.Print(currentNode.data + " ")
        currentNode = currentNode.nextNode
    }
}

func main() {
    var m = &MyLinkedList{}
    m.pushFront("aa")
    m.pushFront("bb")
    print(m)
}

So in your code your just passing the struct by value

To modify struct in runtime you generally use a struct pointer (Golang: I have a map of structs. Why can't I directly modify a field in a struct value?)

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Siva Guru
  • 694
  • 4
  • 12
1

The pushFront function uses the MyLinkedList struct value instead of reference. So if you use value of a variable in a function, it's copy is created in stack. At the end of the function the variables are removed from stack. In the first calling of pushFront function the assigning a node to ll.head is not your original MyLinklist struct it is just a copy of your struct. In the second calling of the pushFront function, againt a copy of your MyLinklist struct will be copied to stack. So its head will be again nil. Then at the end of the function it will be removed from stack. Your original MyLinklist struct which is 'm' will not be changed. So, since it does not change it will print nothing. The solution is that, you should pass your reference of your MyLinklist struct to pushFront function. It is something like following:

func (ll *MyLinkedList) pushFront(data string) *Node {
    node := Node{data, nil}
    if ll.head == nil {
        ll.head = &node
        return ll.head
    }

    node.nextNode = ll.head
    ll.head = &node
    return ll.head
}
computerengineer
  • 109
  • 1
  • 2
  • 8