且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-06-09 01:28:28

题目

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

示例 1:

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

限制:

0 <= 链表长度 <= 10000

我的答案

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


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */

class Solution {
    public int[] reversePrint(ListNode head) {
        //创建一个动态的数组
        ArrayList<Integer> a = new ArrayList<>();
        //遍历链表,并且记录到a这个动态数组中
        ListNode node =head;
        while(node!=null){
            a.add(node.val);
            node=node.next;
        }
        int temp;
        //逆置动态数组
        for(int i=0,j=a.size()-1;i<(a.size())/2;i++,j--){
            temp=a.get(i);
            a.set(i,a.get(j));
            a.set(j,temp);

        }
        //创建int[],用于返回参数
        int[] d = new int[a.size()];
        for(int i = 0;i<a.size();i++){
            d[i] = a.get(i);
        }

         return d;

    }
}


优质答案

    // 执行用时 : 0 ms, 在所有 Java 提交中击败了 100.00% 的用户
    // 内存消耗 : 39.8 MB, 在所有 Java 提交中击败了 100.00% 的用户
    // 不使用栈,不使用递归

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;
    }
}

回顾一下ArrayList

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