题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
时间限制:1秒 空间限制:32768K 热度指数:1083255
解题思路:
有多种解答方案:1,栈 2, 递归
1、对于栈:
/**
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
*
*/
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> arrList = new ArrayList<Integer>();
Stack<Integer> stack = new Stack<Integer>();
//将链表值入栈
while(listNode != null){
stack.push(listNode.val);
listNode = listNode.next;
}
//出栈,进列表
while(!stack.isEmpty()){
arrList.add(stack.pop());
}
return arrList;
}
}
2、对于递归:
/**
* 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> arrList = new ArrayList<Integer>();
if (listNode == null){
return arrList;
}
//调用递归函数,进行逆置输出
reverseList(arrList,listNode);
return arrList;
}
public void reverseList(ArrayList<Integer> arrList,ListNode listNode){
if(listNode.next == null){
arrList.add(listNode.val);
}else{
reverseList(arrList,listNode.next);
arrList.add(listNode.val);
}
}
}