leetcode 链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
题目

解法
从头到尾遍历一次链表,值用栈保存,遍历到链表尾部后对栈中数据输出到数组中
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/class Solution {public int[] reversePrint(ListNode head) {Stack<Integer> stack=new Stack<>();ListNode node=head;while(node!=null){stack.push(node.val);node=node.next;}int[] res=new int[stack.size()];int i=0;while(!stack.isEmpty()){res[i++]=stack.pop();}return res;}}
对链表进行两次遍历,一次获取长度,一次填充数组
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/class Solution {public int[] reversePrint(ListNode head) {// 使用两次遍历,一次获取链表长度,一次填充数组// 遍历游标ListNode cur = head;// 链表长度int len = 0;while (cur != null){len++;cur = cur.next;}int[] res = new int[len];// 重置遍历游标cur = head;while (--len >= 0){res[len] = cur.val;cur = cur.next;}return res;}}
