06从尾到头打印链表
栈实现
class Solution {
public int[] reversePrint(ListNode head) {
Stack<Integer> stack=new Stack();
while(head!=null){
stack.push(head.val);
head=head.next;
}
int[] res=new int[stack.size()];
int i=0;
while(!stack.isEmpty()){
res[i++]=stack.pop();
}
return res;
}
}
递归式的转换
class Solution {
public int[] reversePrint(ListNode head) {
ArrayList<Integer> list =new ArrayList();
recursion(list,head);
int[]res=new int[list.size()];
for(int i=0;i<list.size();i++){
res[i]=list.get(i);
}
return res;
}
public void recursion(ArrayList<Integer> list,ListNode head){
if(head!=null){
if(head.next!=null){
recursion(list,head.next);
}
list.add(head.val);
}
}
}