剑指Offer第三题:从头到尾打印链表
从尾到头打印链表
https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035?tpId=13&tqId=11156&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
题目:输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
解答:
1.栈的方法
public ArrayList<integer> printListFromTailToHead(ListNode listNode){</integer>
Stack<Integer> stack=new Stack<Integer>();
ArrayList<Integer> arrayList=new ArrayList<>();
if(listNode==null){
return arrayList;
}
while(listNode!=null){
stack.push(listNode.val);
listNode=listNode.next;
}
while (!stack.isEmpty()){
arrayList.add(stack.pop());
}
return arrayList;
}2.递归方法
public class Solution {
ArrayList<Integer> arrayList=new ArrayList<>();
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
if (listNode!=null){
printListFromTailToHead(listNode.next);
arrayList.add(listNode.val);
}
return arrayList;
}}