剑指Offer-JZ3-从尾到头打印链表

题目

描述
输入一个链表的头节点,按链表从尾到头的顺序返回每个节点的值(用数组返回)。

如输入{1,2,3}的链表如下图:
在这里插入图片描述

返回一个数组为[3,2,1]

0 <= 链表长度 <= 10000

示例1

输入:
{1,2,3}
返回值:
[3,2,1]

示例2

输入:
{67,0,24,58}
返回值:
[58,24,0,67]

解析

题目要求从尾到头打印链表,但是链表只能从头开始遍历,所以我们可以:
1.采用非递归,利用ArrayList.add(index, object)方法移动元素
2.采用递归方式

解答

一、非递归

/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/
import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> resultList = new ArrayList<>();
        ListNode tmp = listNode;
        while(tmp != null) {
            resultList.add(0, tmp.val);
            tmp = tmp.next;
        }
        return resultList;
    }
}

时间复杂度 O(n^2) 这里算上了ArrayList.add()方法中的复杂度
空间复杂度O(n)

知识点汇总

解答中resultList.add(0, tmp.val); 利用ArrayList.add(index, object)方法进行先进后出操作。

ArrayList.add()如果index下标的位置有元素,那么会将index位置的元素及其以后的元素全部右移,然后在index位置插入新元素object。

看一下ArrayList.add(index, object)源码解析:

    /**
     * Inserts the specified element at the specified position in this
     * list. Shifts the element currently at that position (if any) and
     * any subsequent elements to the right (adds one to their indices).
     *
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public void add(int index, E element) {
        rangeCheckForAdd(index); // 如果index大于数组个数或index小于0,抛出IndexOutOfBoundsException超出边界异常
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        // System.arraycopy方法参数解析  原数组:elementData  从元数据的起始位置开始:index 目标数组:elementData  目标数组的开始起始位置:index + 1  要copy的数组的长度:size - index
        System.arraycopy(elementData, index, elementData, index + 1, size - index); 
        elementData[index] = element;
        size++;
    }

二、递归

/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/
import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> resultList = new ArrayList<>();
        return getArrayList(resultList, listNode);
    }
    private ArrayList getArrayList(ArrayList resultList, ListNode listNode) {
        if (listNode != null) {
            getArrayList(resultList, listNode.next);
            resultList.add(listNode.val);
        }
        return resultList;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值