剑指offer系列:从尾到头打印链表
描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
代码
/** * public class ListNode { * int val; * ListNode next = null; * * ListNode(int val) { * this.val = val; * } * } * */
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> curlist = new ArrayList<>();
ArrayList<Integer> ans2 = new ArrayList<>();
ListNode cur = listNode;
while (cur!=null) {
curlist.add(cur.val);
cur =cur.next;
}
for (int i = curlist.size()-1; i >= 0; i--) {
ans2.add(curlist.get(i));
}
return ans2;
}
}
代码优化
/** * public class ListNode { * int val; * ListNode next = null; * * ListNode(int val) { * this.val = val; * } * } * */
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> curlist = new ArrayList<>();
ListNode cur = listNode;
while (cur!=null) {
curlist.add(0,cur.val);
cur =cur.next;
}
return curlist;
}
}