题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
解法
方法1:先将链表翻转,然后逐个插入,实现代码如下:
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ListNode next = null;//next
ListNode now = listNode;
ListNode pre = null;//pre
ArrayList<Integer> Arr= new ArrayList<Integer>();
if(now == null){
return Arr;
}
else{
while(now != null){
next = now.next;
now.next = pre;
pre = now;
now = next;
}
while(pre != null){
Arr.add(pre.val);
pre = pre.next;
}
return Arr;
}
}
}
方法2:堆栈结构实现,等于使用堆栈翻转链表,更加快捷:
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
Stack<Integer> st = new Stack<Integer>();
ArrayList<Integer> Arr= new ArrayList<Integer>();
while(listNode != null){
st.push(listNode.val);
listNode = listNode.next;
}
while(!st.isEmpty()){
Arr.add(st.pop());
}
return Arr;
}
}