用go语言编写结构体构造函数实现单链表并插入节点
package main
import "fmt"
type ListNode struct { Val int Next *ListNode }
func NewListNode(val int) *ListNode { // 结构体构造函数 return &ListNode{ Val: val, Next: nil, } }
func InsertNode(head *ListNode, val int) *ListNode { // 插入节点 node := NewListNode(val) if head == nil { head = node } else { cur := head for cur.Next != nil { cur = cur.Next } cur.Next = node } return head }
func main() { var head *ListNode head = InsertNode(head, 1) head = InsertNode(head, 2) head = InsertNode(head, 3)
cur := head
for cur != nil {
fmt.Println(cur.Val)
cur = cur.Next
}
}
/* 输出: 1 2 3 */ ``
原文地址: https://www.cveoy.top/t/topic/eQ6J 著作权归作者所有。请勿转载和采集!