Golang程序 用于计算链表中的节点数
实例
解决这个问题的方法
第1步 - 定义一个方法,接受链表的头部。
第2步 - 初始化一个变量,count := 0。
第3步 - 迭代给定的链表,直到它到达最后一个节点。
第4步 – 在循环中增加1的计数。
第5步 - 返回计数。
例子
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 CountNodes(head *Node){
fmt.Printf("Input Linked List is: ")
count :=0
temp := head
for temp != nil {
fmt.Printf("%d ", temp.value)
temp = temp.next
count += 1
}
fmt.Printf("\nNumber of nodes in the linked list is: %d\n", count)
}
func main(){
head := NewNode(30, NewNode(10, NewNode(40, NewNode(40, nil))))
CountNodes(head)
}
输出
Input Linked List is: 30 10 40 40
Number of nodes in the linked list is: 4