GO Program to Implementation of Linked List

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.

How to Implement Linked List:

In this GO program, we are importing the “fmt” package to include some standard libraries into the program. In order to use these library functions, we need to import the “fmt” package. After that Main function starts, inside the main, we are doing the whole program. 

We can say Linked List is the collection of nodes. Each node contains a value and a pointer. 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.

Given below are the steps that are used in the Go program to implement Linked List.

ALGORITHM:

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

Steps to Implement function NewNode(value int):

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

Steps to Implement TraverseLinkedList(head *Node):

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.

GO Source Code

                                          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
   }
}
func main(){
   head := NewNode(100)
   head.next = NewNode(20)
   head.next.next = NewNode(40)
   head.next.next.next = NewNode(70)
   TraverseLinkedList(head)
}

                                      

OUTPUT

Linked List: 100 20 40 70