题目
@Author Tiam
 @Date 2021/12/22 15:37
 @Description: 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)
 Definition for singly-linked list.
 public class ListNode {
 int val;
 ListNode next;
 ListNode(int x) { val = x; }
 }
码
	/**
    * 一. 递归遍历链表, 速度更快
    */
   ArrayList<Integer> tmp = new ArrayList<>();
   public int[] reversePrint1(ListNode head) {
       recur(head);
       int[] res = new int[tmp.size()];
       for(int i = 0; i < res.length; i++) {
           res[i] = tmp.get(i);
       }
       return res;
   }
   void recur(ListNode head) {
       if(head == null) return;
       //递归 反序储存 链表中的值.
       recur(head.next);
       tmp.add(head.val);
   }
   /**
    * 二. 辅助栈法 , 更易理解 ,消耗内存较少
    * @param head
    * @return
    */
   public int[] reversePrint2(ListNode head) {
       //辅助栈 ,先进后出
       LinkedList<Integer> stack = new LinkedList<>();
       while(head != null) {
           //将指定的元素追加到此列表的末尾.
           stack.addLast(head.val);
           head = head.next;
       }
       //创建一个栈大小的数组
       int[] res = new int[stack.size()];
       for(int i = 0; i < res.length; i++) {
           //从此列表中删除并返回最后一个元素。
           res[i] = stack.removeLast();
       }
       return res;
   }
                
                    
                
                
            
        
浙公网安备 33010602011771号