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

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

示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
 
限制:
0 <= 链表长度 <= 10000

解法一:
利用栈先进后出的性质求解。时间复杂度O(n),空间复杂度O(n)。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] reversePrint(ListNode head) {
        Stack<Integer> st = new Stack<>();
        ListNode h = head;
        int count = 0;
        while(h != null){
            st.push(h.val);
            count++;
            h = h.next;
        }
        int[] nums = new int[count];
        for(int j=0;j<count;j++){
            nums[j] = st.pop();
        }
        return nums;
    }
}

解法二:
递归求解

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    int count ,i = 0;
    int[] nums;
    public int[] reversePrint(ListNode head) {    
        if(head != null)
            count++;
        else
            return new int[count];
        nums = reversePrint(head.next);
        nums[i] = head.val;
        i++;
        return nums;
    }
}
posted @ 2021-01-06 15:50  又又又8  阅读(63)  评论(0编辑  收藏  举报