剑指offer 6 - 从尾到头打印链表 - python

223 阅读1分钟

python - 线性数据结构


题目描述

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

示例 1:

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

限制:0 <= 链表长度 <= 10000


从尾到头返回列表中的元素,可以从头到尾遍历链表,将得到的元素不断的插入list的起始位置,然后返回list将相当于返回从尾到头遍历的元素;或者先直接加入在反转list。

e.g. 2 → 5 → 4 2 \rightarrow 5 \rightarrow 4 2→5→4,list的变化: [ ] → [ 2 ] → [ 5 , 2 ] → [ 4 , 5 , 2 ] [] \rightarrow [2] \rightarrow[5,2] \rightarrow [4,5,2] []→[2]→[5,2]→[4,5,2]

class Solution:
    def reversePrint(self, head: ListNode) -> List[int]:
        if head is None: return []

        helper = []

        while head:
            helper.insert(0, head.val)
            head = head.next
            
        return helper
class Solution:
    def reversePrint(self, head: ListNode) -> List[int]:
        if head is None: return []

        helper = []

        while head:
            print(head.val)
            helper.append(head.val)
            head = head.next
        
        return helper[::-1]