To get started with linkedlist please check previous post on how to create singly linkedlist:
Link is as below:
https://sreesindhusruthi.blogspot.com/2021/07/create-single-linked-list-in-golang.html
Now that we have linked list, let's add function to get the length of the linked list.
In previous post we have Node and LinkedList structs created.
Writing function for length.
func (ll *LinkedList) Len() int{ }
This is the function defintion takes linkedlist as input and integer as return type.
Let's write the logic
Step1: Intialize variable with count variable. count := 0
Step2: Check if linkedlist is empty. If it's empty then we return the count as 0.
count := 0
if ll.head == nil{
return 0
}
Step3: As we have to traverse through linked list we need a variable to traverse to each Node.
count := 0
var temp *Node
if ll.head == nil{
return 0
}
temp = ll.head
Step4: we need to loop till there are no more nodes in linkedlist. so the check would be
for temp != nil {}
Step5: now our temp is pointing to head and it;s not nil so will go into the loop, increment the count value, now update temp to next Node of head.
for temp != nil {
count ++
temp = temp.next
fmt.Println(temp)
}
Prints are added for checking if temp is getting updated as expected.
Complete code of this is:
No comments:
Post a Comment