从头到尾打印链表
题目:
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
解答:
链表遍历,数组返回需要获取链表长度,再次遍历链表并从后往前设置数组值即可。
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 class Solution { 10 public int[] reversePrint(ListNode head) { 11 if (head == null) { 12 return new int[]{}; 13 } 14 int len = 0; 15 ListNode node = head; 16 //计算链表长度 17 while (node != null) { 18 len++; 19 node = node.next; 20 } 21 int arr[] = new int[len]; 22 node = head; 23 //反向赋值 24 for (int i = len - 1; i >= 0; i--) { 25 arr[i] = node.val; 26 node = node.next; 27 } 28 return arr; 29 } 30 }

浙公网安备 33010602011771号