从尾到头打印链表

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

 

反转:从头到尾将链表打印到数组中,返回反转后的结果即可。

class Solution:
    def reversePrint(self, head):
        res = []
        while head:
            res.append(head.val)
            head = head.next
        return res[::-1]  # 或者 reverse(res)

 堆栈:利用堆栈先进后出的特点,先依次将元素压入堆栈中,然后将所有元素从堆栈中弹出,即可实现反转。

class Solution:
    def reversePrint(self, head):
        stack= []
        while head:
            stack.append(head.val)
            head = head.next
        res = []
        while stack:
            res.append(stack.pop())
        return res

 

posted @ 2020-08-28 09:00  ninian  阅读(97)  评论(0)    收藏  举报