从尾到头打印链表-剑指offer面试题5

问题描述

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

解题方法

典型后进先出,使用“栈”结构。

/**
 * 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> stack = new Stack<>();
        
        ListNode cur = head;
        while(cur != null){
            stack.push(Integer.valueOf(cur.val));
            cur = cur.next;
        }
        int size = stack.size();
        int[] outarr = new int[size];
        for(int i=0;i<size;i++){
            outarr[i] = stack.pop().intValue();
        }
        return outarr;
    }
}

查询问题

栈的使用

使用方式
还有一个size()函数
JAVA中不建议使用stack

Integer与int之间的转换

Java中Integer和int之间的转换
同上

数组的定义方式

数组定义

递归实现

class Solution {
    ArrayList<Integer> tmp = new ArrayList<Integer>();
    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);
    }
}

存在问题:当链表很长的时候,会导致函数调用的层级很深,从而可能导致函数调用栈溢出。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章