Featured image of post 剑指 Offer 06. 从尾到头打印链表

剑指 Offer 06. 从尾到头打印链表

题目描述

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

示例 1:

  • 输入:head = [1,3,2]
  • 输出:[2,3,1]

限制:

0 <= 链表长度 <= 10000

解法一:递归

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func reversePrint(head *ListNode) []int {
    if head == nil {
        return []int{}
    }
    return append(reversePrint(head.Next), head.Val)
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2023/06/14 13:15:19
comments powered by Disqus
Built with Hugo
主题 StackJimmy 设计