倒叙输出链表的值

public class Project {
public ArrayList<Integer> printListFromTailToHead(Node listNode) {  
       Stack<Integer> stack = new Stack<>();  
       while (listNode != null) {  
           stack.push(listNode.val);  
           listNode = listNode.next;  
       }  
  
       ArrayList<Integer> list = new ArrayList<>();  
       while (!stack.isEmpty()) {  
           list.add(stack.pop());  
       }  
       return list;         
   }  


public static void main(String[] args) {
Node listNode = new Node(1);
listNode.next = new Node(3);
listNode.next.next = new Node(4);
listNode.next.next.next = new Node(0);
Project s = new Project();
System.out.println(s.printListFromTailToHead(listNode));
}

}

public class Node {
int val;
Node next = null;


Node(int val) {
this.val = val;
}
}

猜你喜欢

转载自blog.csdn.net/qq_21406125/article/details/80238480