从尾到头打印链表-剑指Offer

从尾到头打印链表

题目描述

输入一个链表,从尾到头打印链表每个节点的值

输入描述

输入为链表的表头

输出描述

输出为需要打印的“新链表”的表头

思路

  1. 单向链表是从头到尾指向的,从尾到头打印符合“后进先出”,所以我们使用栈结构Stack

代码

import java.util.ArrayList;
import java.util.Stack;
public class Solution03 {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
    ArrayList<Integer> result = new ArrayList<Integer>();
    if (listNode == null) {
        return null;
    }
    Stack stack = new Stack();
    while (listNode != null) {
        stack.add(listNode.val);
        listNode = listNode.next;
    }
    while (!stack.empty()) {
        result.add((Integer)stack.pop());
    }
    return result;
}
}
class ListNode {
    int val;
    ListNode next = null;
    ListNode(int val) {
        this.val = val;
    }
}
原文地址:https://www.cnblogs.com/rosending/p/5608389.html