美文网首页
LeetCode 每日一题 [41] 从尾到头打印链表

LeetCode 每日一题 [41] 从尾到头打印链表

作者: 是小猪童鞋啦 | 来源:发表于2020-06-27 10:53 被阅读0次
LeetCode 从尾到头打印链表 [简单]

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof

示例 1:

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

限制:

0 <= 链表长度 <= 10000

题目分析
解法1

使用ArrayList<>(),遍历链表,然后拿出数据,在进行反序存储到数组输出

解法2

首先获取元素个数 然后再进行第二次迭代赋值

代码实现
public class ReversePrintListNode {

    public static int[] reversePrint2(ListNode head) {
        if (head == null) {
            return new int[]{};
        }
        int len = 0;
        ListNode temp = head;
        while (temp != null) {
            len++;
            temp = temp.next;
        }
        int[] result = new int[len];
        temp = head;
        while (temp != null) {
            result[--len] = temp.val;
            temp = temp.next;
        }
        return result;
    }

    public static int[] reversePrint(ListNode head) {
        if (head == null) {
            return new int[]{};
        }
        ListNode temp = head;
        ArrayList<Integer> res = new ArrayList<>();
        while (temp != null) {
            res.add(temp.val);
            temp = temp.next;
        }
        int[] ints = new int[res.size()];
        int size = res.size();
        for (int i = 0; i <= res.size() - 1; i++) {
            ints[--size] = res.get(i);
        }
        return ints;
    }
}

相关文章

网友评论

      本文标题:LeetCode 每日一题 [41] 从尾到头打印链表

      本文链接:https://www.haomeiwen.com/subject/xbqjahtx.html