剑指offer 3.从尾到头打印链表-CSDN博客

46 阅读1分钟

时间限制:1秒 空间限制:32768K 本题知识点: 链表

题目描述 输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

思路: 将链表存在栈中,先遍历链表进行入栈,然后出栈,实现从尾到头返回

/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList res = new ArrayList();
        Stack s = new Stack();
        ListNode dummyHead = new ListNode(0);
        dummyHead.next = listNode;
        ListNode current = dummyHead;
        while (current.next != null) {
            s.push(current.next.val);
            current = current.next;
        }
        while(!s.isEmpty()) {
            res.add(s.pop());
        }
        return res;
    }
}