1、题目描述
2、题目分析
使用Stack,遍历的时候将链表中的元素添加到栈中。
然后从栈中取出元素,注意要栈要判空,while(! stack.isEmpty())
将从栈中取出的元素存储到List集合中。
返回List集合
注意熟悉这个ListNode数据结构:
/**
* public class ListNode {// 分为值域和 next域
* int val;
* ListNode next = null;
* 初始化的时候对val赋值
* ListNode(int val) {
* this.val = val;
* }
* }
*
*/
3、代码实现
/**
* 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> list = new ArrayList<>();
Stack<ListNode> stack = new Stack<>();
while(listNode != null){
stack.push(listNode);
listNode = listNode.next;
}
while(!stack.isEmpty()){
ListNode l = stack.pop();
list.add(l.val);
}
return list;
}
}