版权声明:转载请保留文章署名和链接 https://blog.csdn.net/u013474436/article/details/88684082
package main
import "fmt"
type ListNode struct {
Val int
Next *ListNode
}
func main() {
list := []int{2,4,3}
head := &ListNode{Val:list[0]}
tail := head //需要头尾两个指针
for i:=1;i<len(list);i++ {
//方法一 数组直接构建链表
tail.Next = &ListNode{Val:list[i]} //tail.Next => (*tail).Next golang的隐式转换
tail = tail.Next
//head.Append(list[i]) //方法二 追加构建链表
}
head.Show()
}
func (h *ListNode) Append(i int) {
for h.Next != nil {
h = h.Next
}
h.Next = &ListNode{Val:i}
}
func (h *ListNode) Show() {
fmt.Println(h.Val)
for h.Next != nil {
h = h.Next
fmt.Println(h.Val)
}
}
示例不够严谨,仅供参考思路