题解 | #从尾到头打印链表# 栈 / 递归
从尾到头打印链表
http://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035
方法一:栈
/**
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
*
*/
import java.util.*;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
Deque<Integer> stack = new ArrayDeque<>();
ListNode cur = listNode;
while (cur != null) {
stack.push(cur.val);
cur = cur.next;
}
return new ArrayList<Integer>(stack);
}
}
方法二:递归
/**
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
*
*/
import java.util.*;
public class Solution {
ArrayList<Integer> list = new ArrayList<Integer>();
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
recur(listNode);
return list;
}
private void recur(ListNode node) {
if (node == null) {
return;
}
recur(node.next);
list.add(node.val);
}
}