【剑指Offer】6.从尾到头打印链表

题目

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

示例 1:

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

解答

源代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] reversePrint(ListNode head) {
        List val = new ArrayList<>();
        while (head != null) {
            val.add(head.val);
            head = head.next;
        }

        int[] res = new int[val.size()];

        for (int i = 0; i < res.length; i++) {
            res[i] = val.get(val.size() - 1 - i);
        }

        return res;
    }
}

总结

大部分题解用的貌似都是栈,我用的就是普通的集合,然后根据头尾索引的数学关系把值存入数组中。

你可能感兴趣的:(剑指Offer,链表,数据结构,leetcode,java)