24

切片指针类型的应用——golang

 3 years ago
source link: https://studygolang.com/articles/30995
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

今天在力扣上做二叉树前序遍历的题目时,遇到一个困惑的问题,先来看看我用递归实现的代码:

func preorderTraversal(root *TreeNode) []int {
    res := make([]int, 0)
    getVal(root, res)
    return res
}
func getVal(node *TreeNode, res []int) {
    if node == nil {return}
    res = append(res, node.Val)
    // fmt.Println(res)
    getVal(node.Left, res)
    getVal(node.Right, res)
}

看着这么简洁优雅的代码,自认是完美无缺、天衣无缝了。可待我点击“执行”,却是提示输出错误,才发现我的输出竟然是空的切片,这让我甚是纳闷,便在递归函数中打印日志,发现切片中确实是有值的呀,可为何等函数返回之后切片的值就不翼而飞了呢?

虽然知道golang中函数的入参都是值传递,可一直都认为切片就相当于C++中的引用呀,那函数中发生了改变,自然原始值也应该跟着变才是。于是便查询资料,才得知切片传入函数中已经不再是原来的切片了,而是生成了一个新的切片,只是两个切片中的指针指向了同一块底层数组而已。也就是说在函数中改变的新切片的值,原始切片还是老样子,这才有了我上面的困惑。

困惑是知晓了,可问题还是得解决,该怎么办呢?可在网络上却未寻得只言片语,正待要放弃时,突发奇想:如果切片也可以有相应的指针类型,那不就可以原始的切片传入函数吗。虽然心里没多少底气,毕竟切片指针看起来都觉得挺别扭的,抱着试试的态度,没想到还真行了。以下是求解的全过程,列位看官请细细品尝:

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func preorderTraversal(root *TreeNode) []int {
    res := make([]int, 0)
    getVal(root, &res)
    return res
}
func getVal(node *TreeNode, res *[]int) {
    if node == nil {return}
    *res = append(*res, node.Val)
    getVal(node.Left, res)
    getVal(node.Right, res)
}

通过解这个题,收获一点心得,遂记录在此,愿后世能有感于斯文,不致惶惶终日而无以解脱。

有疑问加站长微信联系

iiUfA3j.png!mobile

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK