一、题目
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
输入:head = [1,3,2]
输出:[2,3,1]
二、思路
- 遍历链表
- 将链表中的元素存入数组中。
- 倒序打印数组
三、代码
class Solution {
public static int[] reversePrint(ListNode head) {
ListNode node = head;
int count = 0;
while (node != null) {
count++;
node = node.next;
}
int[] nums = new int[count];
while (head != null){
nums[--count] = head.val;
head = head.next;
}
return nums;
}
}
本文介绍了一种通过遍历链表并使用数组存储节点值的方法,实现从尾到头逆序输出链表节点值的算法。输入为链表头节点,输出为逆序数组。
133

被折叠的 条评论
为什么被折叠?



