For a better understanding of this example, we always recommend you to learn the basic topics of Golang programming listed below:
There are so many data structures that we come across in computer programming. In this section, we’ll focus our attention on the Linked list.
A linked list is one of the basic and linear data structures like arrays. It has a bunch of nodes and each node contains the data and a pointer to access the next node. All the elements in the linked list are linked using pointers.
We can say Linked List is the collection of nodes. In this Go program, Head is the starting node of the linked list and it points to the next node. It will continue to generate a linked form as the previous node would store the address of the next node. Finally, the pointer of the last node points to a NULL value. Let's see this with an example, Consider 4 numbers 100, 20, 40,70 which we are going to make nodes of a Linked List
A struct
datatype can be used to create a node of the linked list, it will contain an integer value and a pointer to the next node. Next, we need a function to generate a new node in the linked list(LL), assign values to its variables, and attach the node to that LL. Another function is used to traverse the linked list from head to last and print the values with the help of a loop.
The library functions in Go will help us to implement this program, for that we need to import the fmt package at the start of the program. In the main function, we can call our user-defined functions to create nodes and traverse the linked list.
Given below are the steps that are used in the Go program to implement Linked List.
STEP 1: Start
STEP 2: Define the structure of the node
STEP 3: Assign head as the start node of the linked list by calling the function NewNode(value)
STEP 4: Create the linked list such that the previous node would store the address of the next node by calling the function NewNode(value)
STEP 5: Call the function TraverseLinkedList(head)
STEP 6: Exit
STEP 1: Declare the variable n as Node.
STEP 2: Create node n by assigning data into its node value and changing the pointer of the node as nil.
STEP 3: Return node n
STEP 1: Display all the nodes from the linked list by traversing a list that starts with the head until we find the reference value is NULL.
package main
import "fmt"
type Node struct {
value int
next *Node
}
func NewNode(value int) *Node{
var n Node
n.value = value
n.next = nil
return &n
}
func TraverseLinkedList(head *Node){
fmt.Printf("Linked List: ")
temp := head
for temp != nil {
fmt.Printf("%d -> ", temp.value)
temp = temp.next
}
fmt.Printf("NULL")
}
func main(){
head := NewNode(100)
head.next = NewNode(20)
head.next.next = NewNode(40)
head.next.next.next = NewNode(70)
TraverseLinkedList(head)
}
Linked List: 100 -> 20 -> 40 -> 70 -> NULL