1. 栈(Stack)
package main
import "fmt"
type Stack struct {
items []int
}
func (s *Stack) Push(item int) {
s.items = append(s.items, item)
}
func (s *Stack) Pop() int {
if len(s.items) == 0 {
return -1
}
top := s.items[len(s.items)-1]
s.items = s.items[:len(s.items)-1]
return top
}
func main() {
stack := Stack{}
stack.Push(1)
stack.Push(2)
fmt.Println(stack.Pop())
fmt.Println(stack.Pop())
}
2. 队列(Queue)
package main
import "fmt"
type Queue struct {
items []int
}
func (q *Queue) Enqueue(item int) {
q.items = append(q.items, item)
}
func (q *Queue) Dequeue() int {
if len(q.items) == 0 {
return -1
}
front := q.items[0]
q.items = q.items[1:]
return front
}
func main() {
queue := Queue{}
queue.Enqueue(1)
queue.Enqueue(2)
fmt.Println(queue.Dequeue())
fmt.Println(queue.Dequeue())
}
3. 链表(LinkedList)
package main
import "fmt"
type Node struct {
value int
next *Node
}
type LinkedList struct {
head *Node
}
func (l *LinkedList) Insert(value int) {
newNode := &Node{value: value}
if l.head == nil {
l.head = newNode
} else {
current := l.head
for current.next != nil {
current = current.next
}
current.next = newNode
}
}
func (l *LinkedList) Print() {
current := l.head
for current != nil {
fmt.Print(current.value, " -> ")
current = current.next
}
fmt.Println("nil")
}
func main() {
list := LinkedList{}
list.Insert(1)
list.Insert(2)
list.Insert(3)
list.Print()
}
4. 二叉树(Binary Tree)
package main
import "fmt"
type TreeNode struct {
value int
left *TreeNode
right *TreeNode
}
type BinaryTree struct {
root *TreeNode
}
func (t *BinaryTree) Insert(value int) {
if t.root == nil {
t.root = &TreeNode{value: value}
} else {
insertNode(t.root, value)
}
}
func insertNode(node *TreeNode, value int) {
if value < node.value {
if node.left == nil {
node.left = &TreeNode{value: value}
} else {
insertNode(node.left, value)
}
} else {
if node.right == nil {
node.right = &TreeNode{value: value}
} else {
insertNode(node.right, value)
}
}
}
func (t *BinaryTree) InOrder() {
inOrderTraversal(t.root)
}
func inOrderTraversal(node *TreeNode) {
if node != nil {
inOrderTraversal(node.left)
fmt.Print(node.value, " ")
inOrderTraversal(node.right)
}
}
func main() {
tree := BinaryTree{}
tree.Insert(5)
tree.Insert(3)
tree.Insert(7)
tree.Insert(2)
tree.Insert(4)
tree.InOrder()
}
5. 散列表(HashMap)
package main
import "fmt"
type HashMap struct {
items map[string]int
}
func (h *HashMap) Init() {
h.items = make(map[string]int)
}
func (h *HashMap) Insert(key string, value int) {
h.items[key] = value
}
func (h *HashMap) Get(key string) int {
if value, found := h.items[key]; found {
return value
}
return -1
}
func (h *HashMap) Delete(key string) {
delete(h.items, key)
}
func main() {
hashMap := HashMap{}
hashMap.Init()
hashMap.Insert("a", 1)
hashMap.Insert("b", 2)
fmt.Println(hashMap.Get("a"))
fmt.Println(hashMap.Get("b"))
hashMap.Delete("a")
fmt.Println(hashMap.Get("a"))
}