Golang Program to define a singly linked list.


Examples

Approach to solve this problem

Step 1 − Let’s define a structure of the node.

Step 2 − Make the Linked List such that the previous node would store the address of the next node.

Example

 Live Demo

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(30)
   head.next = NewNode(10)
   head.next.next = NewNode(40)
   head.next.next.next = NewNode(40)
   TraverseLinkedList(head)
}

Output

Linked List: 30 10 40 40

Updated on: 18-Mar-2021

394 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements