To create a linked list in Go, we need to first define a struct that represents a node in the list. The node should have a value
field to store the data and a next
field to point to the next node in the list.
main.go59 chars5 lines
We also need to define a struct to represent the linked list itself. It should have a head
field that points to the first node in the list.
main.go42 chars4 lines
To add a node to the linked list, we can define a method on the LinkedList
struct that takes a value as an argument and creates a new node with that value. If the linked list is empty, the new node becomes the head. Otherwise, we traverse the list to find the last node, and set its next
field to the new node.
main.go277 chars14 lines
To print the values in the linked list, we can define another method on the LinkedList
struct that traverses the list and prints each node's value.
main.go143 chars8 lines
Here's an example usage of the LinkedList
:
main.go138 chars8 lines
Output:
main.go20 chars4 lines
gistlibby LogSnag