LeetCode-从尾到头打印链表

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/

问题

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

示例:

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

输出:[2,3,1]

链表结构

public class ListNode{
    int val;
    ListNode next;
    ListNode(int x){ val = x; }
}

解答

递归实现

i为计数器,记录节点的个数

从最后一个元素开始,向数组中放入自身的值

class Solution {
    public int[] reversePrint(ListNode head) {
        return reverse(head,0);
    }

    public int[] reverse(ListNode head,int i){
        if(head==null){
            return new int[i];
        }
        int[] arr = reverse(head.next,i+1);
        arr[arr.length-i-1] = head.val;
        return arr;
    }
}

执行用时:0ms

内存消耗:40.8MB

栈实现

利用栈先进后出的特点,倒置读取链表的值。

扫描二维码关注公众号,回复: 11294753 查看本文章
class Solution {
    public int[] reversePrint(ListNode head) {
        Stack<ListNode> stack = new Stack<>();
        ListNode temp = head;
        while(temp!=null){
            stack.push(temp);
            temp = temp.next;
        }
        int[] res = new int[stack.size()];
        int cnt = 0;
        while(!stack.isEmpty()){
            res[cnt] = stack.pop().val;
            cnt++;
        }
        return res;
    }
}

执行用时:1ms

内存消耗:40.3MB

猜你喜欢

转载自www.cnblogs.com/HenuAJY/p/13160521.html