思路迭代
先从头到尾存一遍,然后再把该数组倒过来 stack 递归调用
代码展示
stack
import java. util. Stack;
import java. util. ArrayList;
public class Solution {
public ArrayList< Integer> printListFromTailToHead ( ListNode listNode) {
Stack< Integer> stack = new Stack < > ( ) ;
while ( listNode != null) {
stack. push ( listNode. val) ;
listNode = listNode. next;
}
ArrayList< Integer> arrayList = new ArrayList < > ( ) ;
while ( ! stack. isEmpty ( ) ) {
arrayList. add ( stack. pop ( ) ) ;
}
return arrayList;
}
}
递归调用
public class Solution {
public ArrayList< Integer> printListFromTailToHead ( ListNode listNode) {
ArrayList< Integer> arrayList= new ArrayList < Integer> ( ) ;
if ( listNode!= null) {
this . printListFromTailToHead ( listNode. next) ;
arrayList. add ( listNode. val) ;
}
return arrayList;
}
}
注意
遇到循环复杂度过大,大概率是while内没设置好条件,比如:
listNode = listNode.next;