思路一:递归
/** * public class ListNode { * int val; * ListNode next = null; * * ListNode(int val) { * this.val = val; * } * } * */ //递归算法 import java.util.ArrayList; public class Solution { ArrayList<Integer> list = new ArrayList<Integer>(); public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { if(listNode==null){ return list; } printListFromTailToHead(listNode.next); list.add(listNode.val); return list; } }
思路二:借助栈的先进后出特性
1、遍历链表,元素值正序入栈
2、逆序出栈到ArrayList
import java.util.*; /** * 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>(); if(listNode==null){ return list; } Stack<Integer> stack = new Stack<>(); while(listNode!=null){ stack.push(listNode.val); listNode = listNode.next; } while(!stack.isEmpty()){ list.add(stack.pop()); } return list; } }