概念
通过指针将一组零散的内存块串联在一起 , 把内存块称为链表的“结点”。 记录下个结点地址的指针叫作后继指针 next ,第一个结点叫作头结点,把最后一个结点叫作尾结点 。
代码实现
定义单链表
在 golang 中可以通过结构体定义单链表:
// ListNode 单链表
type ListNode struct {Val intNext *ListNode
}
操作单链表
使用 golang 实现单链表常用操作:添加节点、遍历链表、查找链表节点、获取链表长度
// AddNode 添加节点
func AddNode(head *ListNode, v int) *ListNode {newNode := &ListNode{Val: v, Next: nil}if head == nil {return newNode}current := headfor current.Next != nil {current = current.Next}current.Next = newNodereturn head
}// TraverseSingleList 遍历单链表
func TraverseSingleList(t *ListNode) {if t == nil {fmt.Println("-> 空链表!")return}for t != nil {fmt.Printf("%d -> ", t.Val)t = t.Next}fmt.Println()
}// SearchSingleListNode 查找单链表节点
func SearchSingleListNode(t *ListNode, v int) bool {if Head == nil {t = &ListNode{v, nil}Head = treturn false}if v == t.Val {return true}if t.Next == nil {return false}return SearchSingleListNode(t.Next, v)
}// GetSingleListSize 获取链表长度
func GetSingleListSize(t *ListNode) int {if t == nil {fmt.Println("-> 空链表!")return 0}i := 0for t != nil {i++t = t.Next}return i
}