题意:
输入一个链表,按链表值从尾到头的顺序返回一个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
res = []
while listNode:
res.append(listNode.val)
listNode = listNode.next
return res[::-1]
方法二:
递归
# -*- 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
if listNode == None:
return []
p = self.printListFromTailToHead(listNode.next)
return p + [listNode.val]
方法三:
栈
# -*- 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
lit = []
stack = []
if listNode == None:
return lit
while listNode:
lit.append(listNode.val)
listNode = listNode.next
while lit:
stack.append(lit.pop())
return stack