5.从尾到头打印链表 ----《剑指Offer》题解(Java)

题目

输入一个链表的头结点,按照 从尾到头 的顺序返回节点的值。

返回的结果用数组存储。

样例
输入:[2, 3, 5]
返回:[5, 3, 2]

算法思路

将链表遍历一遍,保存到List或者Stack中,再遍历一遍List或Stack即可。
时间复杂度O(n)

代码实现

class Solution {
    public int[] printListReversingly(ListNode head) {
        if(head == null) {
            return null;
        }
        
        List<Integer> list = new ArrayList<Integer>();
        ListNode p = head;
        while(p != null) {
            list.add(p.val);
            p = p.next;
        }
        
        int[] resArr = new int[list.size()];
        int resArrCurIdx = 0;
        for(int i=list.size()-1; i>=0; i--) {
            resArr[resArrCurIdx] = list.get(i);
            resArrCurIdx++;
        }
        return resArr;
    }
}

猜你喜欢

转载自www.cnblogs.com/TatuCz/p/11117218.html