剑指offer-06-从尾到头打印链表

题目:

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

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

思考:

  • 计算链表长度:想要用数组倒序存储链表,如果知道长度的话,可以利用索引很简单的存入;

  • 利用栈数据结构:利用栈先进后出的特性;

  • 利用递归回溯❤:利用递归,走到链表的末尾,在回溯时保存结点,即实现倒序;

题解:

计算链表长度

class Solution {
    public int[] reversePrint(ListNode head) {
        //计算链表长度
        ListNode tmp = head;
        int length = 0;
        while (tmp != null){
            length++;
            tmp = tmp.next;
        }

        int[] res = new int[length];
        for (int i = length-1; i >= 0; i--) {
            res[i] = head.val;
            head = head.next;
        }

        return res;
    }
}

利用栈数据结构

class Solution {
    public int[] reversePrint(ListNode head) {
        //栈
        LinkedList<Integer> stack = new LinkedList<>();
        while (head != null){
            stack.push(head.val);
            head = head.next;
        }

        int[] res = new int[stack.size()];
        for (int i = 0; i < res.length; i++) {
            res[i] = stack.pop();
        }

        return res;
    }
}

利用递归回溯❤

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 < 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);
    }
}

你可能感兴趣的:(刷题笔记,链表,数据结构,java,leetcode)