LeetCode 常用结构之 链表
常用的数据结构
LeetCode 刷题的时候有几个常见的数据结构
其中最常用的是 树
和 链表
所以我把这两个数据结构单独写了两个包
上篇文章已经介绍了树
这篇文章说链表
代码仓库:https://github.com/Han-MeiM/leetCode/tree/...
原文地址:链表、树
树结构
package ListNode
import (
"fmt"
"strconv"
"strings"
)
type ListNode struct {
Val int
Next *ListNode
}
func CreateTestData(data string) *ListNode {
if data == "[]" {
return nil
}
data = string([]rune(data)[1 : len(data)-1])
res := strings.Split(data, ",")
length := len(res)
listNode := make([]ListNode, length)
headVal, err := strconv.Atoi(res[0])
if err != nil {
panic(err)
}
listNode[0] = ListNode{headVal, nil}
for i := 1; i < length; i++ {
headVal, _ = strconv.Atoi(res[i])
listNode[i] = ListNode{headVal, nil}
listNode[i-1].Next = &listNode[i]
}
return &listNode[0]
}
func Print(listNode *ListNode) {
if listNode == nil {
fmt.Println(nil)
}
var buffer strings.Builder
buffer.WriteString("[")
value := strconv.Itoa(listNode.Val)
buffer.WriteString(value)
temp := listNode.Next
for temp != nil {
buffer.WriteString(",")
value = strconv.Itoa(temp.Val)
buffer.WriteString(value)
temp = temp.Next
}
buffer.WriteString("]")
fmt.Println(buffer.String())
}
使用
1.创建链表结构
// 注意不要有空格
list := ListNode.CreateTestData("[1,2,3,4]")
2.打印树结构
ListNode.Print(list)
3.效果
本作品采用《CC 协议》,转载必须注明作者和本文链接