思路:借助栈实现,或使用递归的方法。
代码:
public class NodeListPrint {
//当前节点的值
static class Node{
int val;
Node next;
public Node(int val){
this.val = val;
}
}
//每次放入一个节点值
public static List<Integer> printListFromTailToHead(Node node){
ArrayList<Integer> integerArrayList = new ArrayList<>();
//将数据放入栈中
Stack<Node> integerStack = new Stack<>();
while (null != node){
integerStack.push(node);
node = node.next;
}
while (!integerStack.isEmpty()){
integerArrayList.add(integerStack.pop().val);
}
return integerArrayList;
}
public static void main(String[] args){
Node node = new Node(1);
node.next = new Node(2);
node.next.next = new Node(3);
List<Integer> list = printListFromTailToHead(node);
for (Integer integer : list){
System.out.println(integer);
}
}
}