Golang 程序用于计算链接列表中的节点数。

go programmingserver side programmingprogramming

示例

解决此问题的方法

步骤 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("输入链接列表是:")
   count :=0
   temp := head
   for temp != nil {
      fmt.Printf("%d ", temp.value)
      temp = temp.next
      count += 1
   }
   fmt.Printf("\n链接列表中的节点数是:%d\n", count)
}
func main(){
   head := NewNode(30, NewNode(10, NewNode(40, NewNode(40, nil))))
   CountNodes(head)
}

输出

输入链表为:30 10 40 40
链表中节点数为:4

相关文章