题目:
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 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) {
ListNode node = head;
int cnt = 0;
while(node != null){
cnt++;
node = node.next;
}
int[] res = new int[cnt];
while(head != null){
res[--cnt] = head.val;
head = head.next;
}
return res;
}
}
本文介绍如何通过Java实现从链表尾部到头部的值逆序输出,通过递归或迭代方式详细讲解了Solution类中的reversePrint方法,适合理解链表和数组操作的开发者。
802

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



