每日一练leetconde

从尾到头打印链表

示例 1:

输入:head = [1,3,2]
输出:[2,3,1]

限制:

0 <= 链表长度 <= 10000

此题虽然为一个简单题但是可以体现两种思想

第一种思想就是递归遍历后输出,首先用列表存储递归后的数值,然后存入数组输出

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    ArrayList<Integer> tmp =new ArrayList<>();
    public int[] reversePrint(ListNode head) {
        recur(head);
        int [] res = new int[tmp.size()];
        for(int i = 0;i < tmp.size();i++){
            res[i] = tmp.get(i);
        }
        return res;
    }
    void recur(ListNode head){
        if(head == null){
            return;
        }
        recur(head.next);
        tmp.add(head.val);
    }
}

 第二种思想是栈的数据结构,为什么用栈呢 因为先入后出 也是倒序

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
   
    public int[] reversePrint(ListNode head) {
        LinkedList<Integer> stack = new LinkedList<Integer>();
        while(head != null){
            stack.addLast(head.val);
            head = head.next;
        }
        int [] a = new int[stack.size()];
        for(int i = 0;i < a.length;i++){
            a[i] = stack.removeLast();
        }
        return a;
    }

}

  

原文地址:https://www.cnblogs.com/nenu/p/15061156.html