Description:
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
思路一:
- 用一个list把链表中的元素依次压入,然后对链表进行翻转。
- 注意:python中list.reverse()没有返回值,故不能直接return list.reverse();也不能令list2=list.reverse()再return list2。
# -*- coding:utf-8 -*-
# 运行时间:24ms
# 占用内存:5852k
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
if not listNode:
return []
result=[]
while listNode:
result.append(listNode.val)
listNode=listNode.next
result.reverse()
return result
思路二:
- 考虑栈的特性:先进后出。
# -*- coding:utf-8 -*-
# 运行时间:33ms
# 占用内存:5852k
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
if not listNode:
return []
res=[]
result=[]
while listNode:
res.append(listNode.val)
listNode=listNode.next
while res:
result.append(res.pop())
return result
19.3.15
再次看了下别人的方法,原来这题最简单是思路是用递归(作恍然大悟状hhh)
思路三:
- 递归,依次滑动链表指针,让最前的元素保持在最后。
class Solution:
# -*- coding:utf-8 -*-
#运行时间:30ms
#占用内存:5728k
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
if not listNode:
return []
return self.printListFromTailToHead(listNode.next)+[listNode.val]