输入一个链表,按链表值从尾到头的顺序返回一个ArrayList
class Node{
int val;
Node next;
public Node(int val) {
this.val = val;
}
}
public class Test03 {
public ArrayList<Integer> printListFromTailToHead(Node node){
Stack<Integer> stack =new Stack<>();
while(node!=null){
stack.push(node.val);
node=node.next;
}
ArrayList<Integer> list=new ArrayList<>();
while(!stack.isEmpty()){
list.add(stack.pop());
}
return list;
}
ArrayList<Integer> list =new ArrayList<>();
public ArrayList<Integer> printListFromTailToHead2(Node node){
if(node!=null){
this.printListFromTailToHead2(node.next);
list.add(node.val);
}
return list;
}
public static void main(String[] args) {
Node node01=new Node(21);
Node node02=new Node(23);
Node node03=new Node(25);
node01.next=node02;
node02.next=node03;
Test03 t3=new Test03();
System.out.println(t3.printListFromTailToHead(node01));
System.out.println(t3.printListFromTailToHead2(node01));
}
}