题解 | #从尾到头打印链表#
从尾到头打印链表
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) { ListNode curr = listNode; ArrayList<Integer> list = new ArrayList<>(); while (curr != null) { list.add(curr.val); curr = curr.next; } //反转 Collections.reverse(list); return list; } public ArrayList<Integer> printListFromTailToHead2(ListNode listNode) { //先反转 ListNode curr = listNode; ListNode prev = null; while (curr != null) { ListNode next = curr.next; curr.next = prev; prev = curr; curr = next; } ArrayList<Integer> list = new ArrayList<>(); while (prev != null) { list.add(prev.val); prev = prev.next; } return list; } }
我这里从尾到头打印链表有两个方案:
1、先遍历链表实现链表的反转,然后再次遍历装入 list 中
2、先遍历链表装入 list 中,然后通过 Collections.reverse 方法反转 list