Golang Program to Insert a Node as First Node in a Given Linked List.


February 22, 2022, Learn eTutorial
1277

For a better understanding of this example, we always recommend you to learn the basic topics of Golang programming listed below:

As we know a linked list is a collection of nodes. Each node has its own data and a pointer which helps you to access the next node of the linked list. That means all the elements in the linked list are linked using pointers.

Suppose we want to add a new node at the beginning of the given linked list, we can follow this Golang program. In this program, we’ll focus our attention on how to add a node as the first node in a given linked list by using GO language.

There is an fmt package which used to import some standard libraries into the program. Use the built-in function fmt.println() to print anything on the screen and fmt.scanln() for reading the data. These functions are defined under the fmt package. So we need to import the “fmt” package to use these functions. After that, open the main function. We are doing the whole program inside the main function, which is the starting point of our program.

Here we use a structure to define a node. Generate linked list by calling the function NewNode that creates nodes by assigning data into its node value and changing the pointer of the node as next node. Now the head is the starting node of the linked list. 
Display all the nodes from the linked list by calling the function TraverseLinkedList(head) that traversing a list starts with the head until we find the reference value is NULL.

Now you have a linked list. Whenever you want to add a node as a first node in the given linked list, read the data you want to add as the first node by using fmt.scanln and passing it to the function AddFirstNode. This function defines a method that accepts the head of a linked list. Check using if head equal to nil. If so; create a new node and return that node as head. Otherwise, update the head of the input linked list. Finally, display the updated linked list by calling the function TraverseLinkedList.

Given below are the steps that are used in the Go program to add the first node in a given linked list.

ALGORITHM:

STEP 1: Start
STEP 2: Define a structure of the node
STEP 3: Create a linked list by calling the function NewNode(). Here the head is the start node of the linked list.
STEP 4: Display input linked list by calling the function TraverseLinkedList(head).
STEP 5: Read the new data which you want to insert into the linked list as an item
STEP 6: Add the new node at the beginning of the linked list by calling head = InsertFirstNode(head,item). 

STEP7: At last, make the new node is the first node of the list
STEP 8: Display the linked list after adding the first node by calling the function TraverseLinkedList(head).
STEP 9: Exit

Steps to Implement 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 the next node. 
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 nil.

Steps to Implement AddFirstNode(head *Node, data int)

Step 1: Define a method that accepts the head of the linked list.
Step 2: If head == nil, create a new node and return that node as head.
Step 3: If the head is not nil, then update the head of the input linked list such as

  • Allocate memory for new node ptr and store data into the data part of the ptr.
  • Make the linked part of the new node ptr pointing to the existing first node i.e.; head of the list.
  • Return new node ptr.

Golang Source Code

                                          package main
import "fmt"
type Node struct {
   value int
   next *Node
}
func NewNode(value int, next *Node) *Node{
   var n Node
   n.value = value
   n.next = next
   return &n
}
func TraverseLinkedList(head *Node){
   temp := head
   for temp != nil {
      fmt.Printf("%d ", temp.value)
      temp = temp.next
   }
   fmt.Println()
}
func InsertFirstNode(head *Node, data int) *Node{
  if head == nil{
    head = NewNode(data, nil)
    return head
   }
   ptr := NewNode(data, nil)
  ptr.next = head
  fmt.Println("\nNode inserted\n") 
return ptr

}

func main(){
   head := NewNode(30, NewNode(10, NewNode(40, NewNode(40, nil))))
   fmt.Printf("Input Linked list is: ")
   TraverseLinkedList(head)
var item int;
fmt.Printf ("\nEnter the item which you want to insert?\n") 
        fmt.Scan(&item;)
       head = InsertFirstNode(head,item)  

   fmt.Println("After adding the first node, the linked list is: ")
   TraverseLinkedList(head)
}


                                      

OUTPUT

Input Linked list is: 30 10 40 40 

Enter the item which you want to insert?
90

Node inserted

After adding the first node, the linked list is: 
90 30 10 40 40