题解 | #从尾到头打印链表#
从尾到头打印链表
https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035
import java.util.*; /** * 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> res = new ArrayList<>(); if (listNode == null) return res; while (listNode != null) { res.add(listNode.val); listNode = listNode.next; } int size = res.size(); ListIterator<Integer> fwd = res.listIterator(); ListIterator<Integer> rev = res.listIterator(size); for (int i = 0, mid = size >> 1; i < mid; i++) { Integer tmp = fwd.next(); fwd.set(rev.previous()); rev.set(tmp); } return res; } }
思路:
将链表中的数据保存到ArrayList中,最后将顺序反转。
#剑指OFFER#