Wednesday, July 7, 2021

Print elements of linkedlist - Golang

 This is 3rd post on linked list. For previous posts, pls check the links below:

https://sreesindhusruthi.blogspot.com/2021/07/create-single-linked-list-in-golang.html

https://sreesindhusruthi.blogspot.com/2021/07/length-of-linkedlist-implementation-in.html

Writing print function for linked list to print elements.

The function name is Print and elements data is available in Node.data .

Step1: Check if linked list is empty. If empty print "NULL"

Step2: Print Node.data and update head to next Node in the linkedlist.

The function code is :

func (ll *LinkedList) Print() {
if ll.head == nil{
fmt.Print("NULL")
return
}
//No Intermediate variable is used so we are traversing on
//the actual object created and it's references gets updated on updating ll.head.
for ll.head != nil {
fmt.Printf("%+v -->",ll.head.data)
ll.head = ll.head.next
ll.Print()
}
}

Complete code:

package main
import "fmt"
type Node struct{
data int
next *Node
}
func (n *Node) NewNode(data int, next *Node){
n.data = data
n.next = next
}
type LinkedList struct{
head *Node
}
func (ll *LinkedList) Len() int{
count := 0
var temp *Node
if ll.head == nil{
return 0
}
temp = ll.head
//fmt.Println(temp)
for temp != nil {
count ++
temp = temp.next
//fmt.Println(temp)
}
return count
}
func (ll *LinkedList) Print() {
if ll.head == nil{
fmt.Print("NULL")
return
}
for ll.head != nil {
fmt.Printf("%+v -->",ll.head.data)
ll.head = ll.head.next
ll.Print()
}
}
func main(){
llist := new(LinkedList)
node1 := new(Node)
node1.NewNode(3, nil)
llist.head = node1
//fmt.Println(llist.Len())
node2 := new(Node)
node2.NewNode(7, nil)
llist.head.next = node2
//fmt.Println(llist.Len())
node3 := new(Node)
node3.NewNode(10, nil)
llist.head.next.next = node3
llist.Print()
}
/*
output:
3 -->7 -->10 -->NULL
*/


No comments:

Post a Comment