第2日 从尾到头打印链表
题目链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
题目
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
解题
-
数组
大致思路:
创建一个足够大的数组,遍历链表且把元素的值按顺序存进数组;
遍历结束后,再创建一个大小刚好的数组,再逆序放进去。
详细代码如下:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public int[] reversePrint(ListNode head) { if (head==null) return null;