题目
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
解法一:递归(递归本来就是一种栈,所以算做一类)
func reversePrint(head *ListNode) []int {if head == nil {return []int{}}if head.Next == nil {return []int{head.Val}}return append(reversePrint(head.Next), head.Val)
}
解法二:逆置链表
func reversePrint(head *ListNode) []int {if head == nil {return []int{}}// 逆置链表fistNode, mindNode := head, head.NextfistNode.Next = nilfor {if mindNode == nil {break}endNode := mindNode.NextmindNode.Next = fistNodefistNode = mindNodemindNode = endNode}vals := make([]int,0)for {if fistNode == nil {return vals}vals = append(vals, fistNode.Val)fistNode = fistNode.Next}
}
解法三:头部动态插入(模拟切片动态扩容)
func reversePrint(head *ListNode) []int {if head == nil {return []int{}}vals := make([]int, 4)endIndex := len(vals)for {endIndex--if head == nil {break}vals[endIndex] = head.Valif endIndex == 0 {vals, endIndex = dilatation(vals)}head = head.Next}return vals[endIndex+1:]
}func dilatation(arr []int) ([]int, int) {lenArr := len(arr)restfulSize := lenArr + lenArr/2restful := make([]int, restfulSize)endIndex := len(restful)arrIndex := lenArr - 1for {if arrIndex < 0 {break}endIndex--restful[endIndex] = arr[arrIndex]arrIndex--}return restful, endIndex
}
总结:可以看出头部动态插入与逆置链表再执行速度相同的情况下占用的空间还是比递归少一些,虽然不是官方解法。