从尾到头打印链表
代码实现
package 剑指offer;
import java.util.ArrayList;
import java.util.Stack;
/**
* @author WangXiaoeZhe
* @Date: Created in 2019/11/22 14:57
* @description:
*/
public class Main3 {
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public static void main(String[] args) {
}
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> list = new ArrayList<>();
Stack<Integer> stack = new Stack<>();
while (listNode != null) {
stack.push(listNode.val);
listNode = listNode.next;
}
while (!stack.empty()) {
list.add(stack.pop());
}
return list;
}
}