剑指 Offer 06. 从尾到头打印链表(Java)

256 阅读1分钟

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

解题思路

先确定数组的长度,在逆序装进数组就可以了。

直接两遍遍历即可

solution

  1. 先遍历链表一遍确定数组长度
  2. 再遍历一边逆序装进数组

代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] reversePrint(ListNode head) {
        int len = 0;
        ListNode cur = head;
        while(cur != null){
            cur = cur.next;
            len++;
        }
        int[] arr = new int[len];
        while(head != null){
            arr[len-1] = head.val;
            head = head.next;
            len--;
        }
        return arr;
    }
}