Golang Program to insert a node at the ith index node, when the index is at the 0th position in the linked list.


Examples

Approach to solve this problem

Step 1 − Define a method that accepts the head of a linked list.

Step 2 − If head == nil, create a new node and make it head and return it as the new head.

Step 3 − When index == 0, then update the head.

Step 4 − Iterate the given linked list from its head. Also, initialize preNode that will keep the store address of the previous node.

Step 5 − If index i matches with the given index, then then delete that node.next, break the loop.

Step 6 − Return, at the end of loop.

Example

 Live Demo

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 InsertNodeAtIthIndex(head *Node, index, data int) *Node{
   if head == nil{
      head = NewNode(data, nil)
      return head
   }
   if index == 0{
      newNode := NewNode(data, nil)
      newNode.next = head
      head = newNode
      return head
   }
   i := 0
   temp := head
   preNode := temp
   for temp != nil {
      if i == index{
         newNode := NewNode(data, nil)
         preNode.next = newNode
         newNode.next = temp
         break
      }
      i++
      preNode = temp
      temp = temp.next
   }
   return head
}
func main(){
   head := NewNode(30, NewNode(10, NewNode(40, NewNode(40, nil))))
   fmt.Printf("Input Linked list is: ")
   TraverseLinkedList(head)
   index := 0
   head = InsertNodeAtIthIndex(head, index, 5)
   fmt.Printf("Inserting new node at %dth index, Linked List is: ", index)
   TraverseLinkedList(head)
}

Output

Input Linked list is: 30 10 40 40
Inserting new node at 0th index, Linked List is: 5 30 10 40 40

Updated on: 18-Mar-2021

295 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements