Skip to main content

Find length of circular linked list in golang

Go program for Find length of circular linked list . Here more information.

package main
import "fmt"
// Go program for
// Count number of nodes in circular linked list 

// Define strcut of linked list Node
type LinkNode struct {
	data int
	next * LinkNode
}
func getLinkNode(data int, first * LinkNode) * LinkNode {

	return &LinkNode {data,first}
}
type CircularLinkedList struct {
	head * LinkNode
}
func getCircularLinkedList() * CircularLinkedList {

	return &CircularLinkedList {nil}
}
// Insert node at end of circular linked list
func(this *CircularLinkedList) insert(value int) {
	// Create a new node
	var node * LinkNode = getLinkNode(value, this.head)
	if this.head == nil {
		// First node of linked list
		this.head = node
		node.next = this.head
	} else {
		var temp * LinkNode = this.head
		// Find the last node
		for (temp.next != this.head) {
			// Visit to next node
			temp = temp.next
		}
		// Add new node at the last 
		temp.next = node
	}
}
func(this CircularLinkedList) countNode() int {
	if this.head == nil {
		return 0
	}
	// Start with second node
	var temp * LinkNode = this.head.next
	// This is used to count linked node
	var count int = 1
	// iterate circular linked list
	for (temp != this.head) {
		count += 1
		// Visit to next node
		temp = temp.next
	}
	return count
}
func main() {
	var cll * CircularLinkedList = getCircularLinkedList()
	// Add nodes
	cll.insert(1)
	cll.insert(3)
	cll.insert(5)
	cll.insert(7)
	cll.insert(9)
	cll.insert(11)
	// Display result
	fmt.Println(cll.countNode())
}

Output

6




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment