python3从尾到头打印链表

题目描述

输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

方法一:通过栈实现

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        # write code here
        stack = []
        while listNode != None:
            stack.append(listNode.val)
            listNode = listNode.next
        ArrayList =[]
        while stack:
            ArrayList.append(stack.pop())
        return ArrayList

 方法二:通过递归实现

# -*- coding:utf-8 -*-
#class ListNode:
#    def __init__(self, x):
#        self.val = x
#        self.next = None

class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        # write code here
        # @listNode: 头结点
        if listNode is None:
            return []
        return self.printListFromTailToHead(listNode.next) + [listNode.val]
posted @ 2018-08-16 13:44  耐烦不急  阅读(431)  评论(0编辑  收藏  举报