时间限制:1秒 空间限制:32768K 热度指数:681780
本题知识点: 链表
题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
思路:
从尾到头打印链表首先想到的是利用栈的性质:先进后出,在此注意,写完代码,一定要导Stack包
/**
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
*
*/
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
//从尾到头顺序返回,类似于栈的结果,先进后出
Stack<Integer> stack = new Stack<Integer>();
while(listNode != null){
stack.push(listNode.val);
listNode = listNode.next;
}
ArrayList<Integer> newList = new ArrayList<Integer>();
while(!stack.isEmpty()){
newList.add(stack.pop());
}
return newList;
}
}