剑指offer06从尾到头打印链表

57 阅读1分钟

🍀从尾到头打印链表

描述:

 # 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
 ​
 示例 1:
 输入:head = [1,3,2]
 输出:[2,3,1]
  
 ​
 限制:
 0 <= 链表长度 <= 10000

思考:

反向输出链表,大一时候的基础题,不过之前是用c做的,这次看大神用java定义类做,第一次看到这样的形式,忘记了java把链表舍弃了。

实现:

 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];
         node = head;
         for (int i = count - 1; i >= 0; --i) {
             nums[i] = node.val;
             node = node.next;
         }
         return nums;
     }
 }

测试一下!

image.png