一、题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
二、代码实现
方法一、遍历,存在list中,反转list
# -*- 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
nodevallist = []
while listNode:
nodevallist.append(listNode.val)a
listNode = listNode.next
return nodevallist[::-1]
方法二、遍历,记录在stack里,然后pop出来
# -*- 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:
stack.append(listNode.val)
listNode = listNode.next
res = []
while stack:
res.append(stack.pop())
return res
方法三、递归,直到链表尾,再返回
# -*- 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 = []
if not listNode: return res
def recursive(listNode):
if not listNode.next:
res.append(listNode.val)
else:
recursive(listNode.next)
res.append(listNode.val)
recursive(listNode)
return res
精简后:
# -*- 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 = []
if not listNode: return res
def recursive(listNode):
if listNode.next:
recursive(listNode.next)
res.append(listNode.val)
recursive(listNode)
return res
网友评论