输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
===============Python=============
# -*- 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 not listNode: return [] res = [] while listNode: res.append(listNode.val) listNode = listNode.next return res[::-1]
==============Java============
/** * public class ListNode { * int val; * ListNode next = null; * * ListNode(int val) { * this.val = val; * } * } * */ import java.util.ArrayList; public class Solution { public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { ArrayList<Integer> res = new ArrayList<>(); if (listNode == null) { return res; } addList(res, listNode); return res; } public void addList(ArrayList<Integer> res, ListNode listNode) { if (listNode != null){ addList(res, listNode.next); res.add(listNode.val); } } }