今天我们来做一道LeetCode上的题目,原题链接:剑指 Offer 06. 从尾到头打印链表
题目描述
- 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
- 示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
- 限制:
0 <= 链表长度 <= 10000
思路分析
- 翻转数组
- 先进先出栈
- 递归思路
代码
# Python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reversePrint(self, head):
"""
:type head: ListNode
:rtype: List[int]
"""
# # 1.
# res = []
# while head:
# res.append(head.val)
# head = head.next
# return res[: : -1]
# 2.
stack, res = collections.deque(), []
while head:
stack.append(head.val)
head = head.next
while stack:
res.append(stack.pop())
return res
# # 3
# def recur(node):
# if not node:
# return
# recur(node.next)
# res.append(node.val)
# res = []
# recur(head)
# return res
总结
- 翻转数组最简洁
- 先进后出栈较通用
- 递归逻辑相对绕一些
附录
本文正在参与「掘金 2021 春招闯关活动」, 点击查看 活动详情