题目:输入一个链表,从尾到头打印链表每个节点的值。
思路:将每个节点的值存入栈中,再依次出栈打印。也可以使用递归来解决。
代码如下:
/**
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
*
*/
import java.util.*;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> arrayList=new ArrayList<>();
if(listNode==null){
return arrayList;
}
ListNode cur=listNode;
Stack<ListNode> stack=new Stack<>();
while (cur!=null){
stack.push(cur);
cur=cur.next;
}
while (!stack.empty()){
ListNode pop = stack.pop();
arrayList.add(pop.val);
}
return arrayList;
}
}