/**
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
*
*/
/*
*利用栈实现
*/
import java.util.ArrayList;
import java.util.Stack;
import java.util.List;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
//定义一个指针,指向头结点
ListNode index=listNode;
Stack<Integer> newSpace=new Stack<Integer>();
ArrayList<Integer> resultList=new ArrayList<Integer>();
while(index!=null){
newSpace.push(index.val);
index=index.next;
}
while(!newSpace.isEmpty()){
for(int i=0;i<newSpace.size();i++){
resultList.add(newSpace.pop());
}
}
return resultList;
}
}
时间复杂度:O(2n)
空间复杂度:O(n)