Day17:从尾到头打印链表

45 阅读1分钟

描述

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

如输入{1,2,3}的链表如下图:

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

0 <= 链表长度 <= 10000

示例1

输入:

{1,2,3}

返回值:

[3,2,1]

示例2

输入:

{67,0,24,58}

返回值:

[58,24,0,67]
import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ListNode currentNode = listNode;
        ArrayList<Integer> tempList = new ArrayList<Integer>();

        while(currentNode != null){
            tempList.add(currentNode.val);
            currentNode = currentNode.next;
        }
        // 翻转
        ArrayList<Integer> endList = new ArrayList<Integer>();
        for(int i=tempList.size()-1; i>=0; i--){
            endList.add(tempList.get(i));
        }
        return endList;
    }
}