创建两个ArrayList,一个用来根据传进来的ListNode参数新建一个完整的ArrayList,另一个用来存储反转后的ArrayList.
使用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> list = new ArrayList<Integer>();
ArrayList<Integer> result = new ArrayList<Integer>();
ListNode temp = listNode;
while (temp != null) {
list.add(temp.val);
temp = temp.next;
}
for (int i = list.size()-1;i >= 0;i--){
result.add(list.get(i));
}
return result;
}
}
使用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
current = listNode
node_list = []
while current:
node_list.append(current.val)
current = current.next
node_list.reverse()
return node_list