Fix "函数" and "方法"

This commit is contained in:
krahets
2023-06-24 16:37:56 +08:00
parent 674ff2910a
commit 504dff1728
10 changed files with 18 additions and 18 deletions
+5 -5
View File
@@ -8,14 +8,14 @@ package chapter_heap
// 实现 heap.Interface 需要同时实现 sort.Interface
type intHeap []any
// Push heap.Interface 的方法,实现推入元素到堆
// Push heap.Interface 的函数,实现推入元素到堆
func (h *intHeap) Push(x any) {
// Push 和 Pop 使用 pointer receiver 作为参数
// 因为它们不仅会对切片的内容进行调整,还会修改切片的长度。
*h = append(*h, x.(int))
}
// Pop heap.Interface 的方法,实现弹出堆顶元素
// Pop heap.Interface 的函数,实现弹出堆顶元素
func (h *intHeap) Pop() any {
// 待出堆元素存放在最后
last := (*h)[len(*h)-1]
@@ -23,18 +23,18 @@ func (h *intHeap) Pop() any {
return last
}
// Len sort.Interface 的方法
// Len sort.Interface 的函数
func (h *intHeap) Len() int {
return len(*h)
}
// Less sort.Interface 的方法
// Less sort.Interface 的函数
func (h *intHeap) Less(i, j int) bool {
// 如果实现小顶堆,则需要调整为小于号
return (*h)[i].(int) > (*h)[j].(int)
}
// Swap sort.Interface 的方法
// Swap sort.Interface 的函数
func (h *intHeap) Swap(i, j int) {
(*h)[i], (*h)[j] = (*h)[j], (*h)[i]
}
+2 -2
View File
@@ -13,14 +13,14 @@ import (
)
func testPush(h *intHeap, val int) {
// 调用 heap.Interface 的方法,来添加元素
// 调用 heap.Interface 的函数,来添加元素
heap.Push(h, val)
fmt.Printf("\n元素 %d 入堆后 \n", val)
PrintHeap(*h)
}
func testPop(h *intHeap) {
// 调用 heap.Interface 的方法,来移除元素
// 调用 heap.Interface 的函数,来移除元素
val := heap.Pop(h)
fmt.Printf("\n堆顶元素 %d 出堆后 \n", val)
PrintHeap(*h)
+2 -2
View File
@@ -15,14 +15,14 @@ type maxHeap struct {
data []any
}
/* 构造方法,建立空堆 */
/* 构造函数,建立空堆 */
func newHeap() *maxHeap {
return &maxHeap{
data: make([]any, 0),
}
}
/* 构造方法,根据切片建堆 */
/* 构造函数,根据切片建堆 */
func newMaxHeap(nums []any) *maxHeap {
// 将列表元素原封不动添加进堆
h := &maxHeap{data: nums}