剑指Offer 面试题05:从尾到头打印链表

从尾到头打印链表

题目描述

输入一个链表,按链表从尾到头的顺序返回一个ArrayList

解题思路

先遍历一次链表,得到链表长度。初始化一个该长度的数组,再一次遍历链表,将链表元素值从数组尾部开始加入。最后将数组转为ArrayList

这里的遍历链表顺序与最终需要的结果顺序刚好相反。如果可以直接使用栈,或自己实现一个栈,则可以先把链表元素按顺序入栈,全部元素入栈以后再逐一出栈。

代码

/**
*    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) {
        if (listNode != null) {
            // 先遍历一次链表,得到链表长度
            int listNodeLength = 0;
            ListNode currentListNode = listNode;
            do {
                listNodeLength++;
                currentListNode = currentListNode.next;
            } while (currentListNode != null);
            
            int[] resultArray = new int[listNodeLength];
            
            // 再一次遍历链表,将链表元素值从数组尾部开始加入
            int resultArrayIndex = listNodeLength - 1;
            currentListNode = listNode;
            do {
                resultArray[resultArrayIndex] = currentListNode.val;
                currentListNode = currentListNode.next;
                resultArrayIndex--;
            } while (currentListNode != null);
            
            // 数组转为ArrayList
            ArrayList<Integer> resultArrayList = new ArrayList<>(listNodeLength);
            for (int i = 0; i < resultArray.length; i++) {
                resultArrayList.add(resultArray[i]);
            }
            return resultArrayList;
        } else {
            return new ArrayList<Integer>(0);
        }
    }
}