【LeetCode 剑指offer 06】输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

学习目标:

目标:熟练运用Java数据结构知识


学习内容:

本文内容:使用Java实现:输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。


题目描述

示例 1:

输入:head = [1,3,2]
输出:[2,3,1]

解题思路:

首先获取链表长度,创建大小为链表长度的数组,然后遍历链表,依次将元素从尾到头的放入数组

实现代码:

public static int[] reversePrint(Node head) {
        Node cur=head;
        if(cur==null){
            return  new int[]{};
        }
        int count=0;//获取链表长度
        while(cur!=null){
            count++;
            cur=cur.next;
        }
        cur=head;
        int[] result=new int[count];
        //将链表元素放入数组中
        for(int i=count-1;i>=0;i--){
            result[i]=cur.val;
            cur=cur.next;
        }
        return result;
    }