剑指offer06--从尾到头打印链表。Java实现,搞定Java。

  • 题目描述
    在这里插入图片描述
  • 思路:思路相对简单,利用栈先进后出的特性,先将链表值push()入栈,然后建立数组,将栈内值依次pop()存入数组,返回数组即可。
  • 代码
class Solution {
    
    
    public int[] reversePrint(ListNode head) {
    
    
        //使用栈,先将链表值push()入栈,然后建立数组,将栈内值pop()存入数组
        Stack<ListNode> stack = new Stack();
        ListNode temp = head;
        while(temp != null){
    
    
            stack.push(temp);
            temp = temp.next;
        }
        int size = stack.size();
        int[] arr = new int[size];
        for(int i = 0;i < size;i++){
    
    
            arr[i] = stack.pop().val;
        }
        return arr;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44809329/article/details/109238298