题目
描述
输入一个链表的头节点,按链表从尾到头的顺序返回每个节点的值(用数组返回)。
如输入{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;
}
}