题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
解题思路
1、先将链表反转,然后再将里面的值赋给ArrayList;
2、使用递归,将链表里的值从后到前赋给ArrayList。
代码
代码一:
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> list = new ArrayList<>();
if(listNode == null){
return list;
}
ListNode pre = listNode;
ListNode cur = listNode;
ListNode next = listNode.next;
while(next != null){
cur.next = next.next;
next.next = pre;
pre = next;
next = cur.next;
}
while(pre != null){
list.add(pre.val);
pre = pre.next;
}
return list;
}
}
代码二:
链接:https://www.nowcoder.com/questionTerminal/d0267f7f55b3412ba93bd35cfa8e8035?f=discussion
来源:牛客网
public class Solution {
ArrayList<Integer> arrayList=new ArrayList<Integer>();
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
if(listNode!=null){
this.printListFromTailToHead(listNode.next);
arrayList.add(listNode.val);
}
return arrayList;
}
}