問題:
實現(xiàn)一個單鏈表(給一個切片,將其寫入到一個單鏈表中)
代碼示例:
package main
import "fmt"
// 時間:2021-10-29
// 功能:實現(xiàn)一個單鏈表(給一個切片,將其寫入到一個單鏈表中)
type node struct {
data int
next *node
}
func main() {
slice := []int{1, 5, 9, 23, 8, 999}
link := solve(slice)
nowNode := link
for nowNode != nil {
fmt.Println(nowNode.data)
nowNode = nowNode.next
}
}
func solve(slice []int) *node {
myNode := new(node)
if len(slice) < 1 {
return nil
}
myNode.data = slice[0]
head := myNode
for _, val := range slice[1:] {
tempNode := new(node)
tempNode.data = val
myNode.next = tempNode
myNode = tempNode
}
return head
}