图和节点概念介绍图是由顶点集合和边集合组成的数据结构。节点即为图中的顶点,可以包含额外的信息如键值对。边连接两个节点,表示节点之间的关系。示例代码typeGraphstruct{adjListmap[int][]int}funcNewGraph()*Gra
概念介绍
示例代码
type Graph struct {
adjList map[int][]int
}
func NewGraph() *Graph {
return &Graph{adjList: make(map[int][]int)}
}
func (g *Graph) AddEdge(v1, v2 int) {
g.adjList[v1] = append(g.adjList[v1], v2)
g.adjList[v2] = append(g.adjList[v2], v1)
}
分析方法
基本定义
示例代码
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func NewTreeNode(val int) *TreeNode {
return &TreeNode{Val: val}
}
实现原理
示例代码
type HashTable struct {
size int
data []interface{}
}
func NewHashTable(size int) *HashTable {
return &HashTable{size: size, data: make([]interface{}, size)}
}
func (h *HashTable) put(key string, value interface{}) {
hash := hashFunction(key, h.size)
h.data[hash] = value
}
func hashFunction(key string, size int) int {
var hash int
for _, v := range key {
hash += int(v)
}
return hash % size
}
特点
示例代码
type ListNode struct {
Val int
Next *ListNode
}
func NewListNode(val int) *ListNode {
return &ListNode{Val: val}
}
双端链表允许从两端插入或删除元素。
示例代码
type DoubleNode struct {
Val int
Prev *DoubleNode
Next *DoubleNode
}
func NewDoubleNode(val int) *DoubleNode {
return &DoubleNode{Val: val}
}
先进先出(FIFO)原则。
示例代码
type Queue struct {
front *ListNode
rear *ListNode
}
func NewQueue() *Queue {
return &Queue{}
}
func (q *Queue) Enqueue(val int) {
node := NewListNode(val)
if q.rear == nil {
q.front = node
q.rear = node
} else {
q.rear.Next = node
q.rear = node
}
}
后进先出(LIFO)原则。
示例代码
type Stack struct {
top *ListNode
}
func NewStack() *Stack {
return &Stack{}
}
func (s *Stack) Push(val int) {
node := NewListNode(val)
node.Next = s.top
s.top = node
}
Go 的 container 包提供了多种高效的数据结构实现,包括:
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!