从头到尾打印链表 (链表/栈)

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

示例 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 {
    public int[] reversePrint(ListNode head) {
        ListNode node = head;
        int length = 0;
        while(node!=null) {
            length++;
            node=node.next;
        }

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

方法二:利用栈先进后出的特性

/**
 * 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<ListNode> stack = new Stack<>();
        ListNode node = head;
        while (node != null) {
            stack.push(node);
            node = node.next;
        }

        int length = stack.size();
        int[] array = new int[length];
        for (int i = 0; i < length; i++) {
            array[i] = stack.pop().val;
        }
        return array;
    }
}
posted @ 2021-03-25 16:39  halo623  阅读(94)  评论(0编辑  收藏  举报