剑指Offer06从尾到头打印链表java题解

时间复杂度空间复杂度都是O(N)

1.我怎么就想不到用栈呢。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] reversePrint(ListNode head) {
        LinkedList<Integer> stack=new LinkedList<>();
        int count=0;
        while(head!=null){
            stack.addLast(head.val);
            count++;
            head=head.next;
        }
        int[] res=new int[count];
        for(int i=0;i<count;i++){
            res[i]=stack.removeLast();
        }
        return res;
    }
}

在这里插入图片描述

2.

开的数组太大了,不好。

代码

class Solution {
    public int[] reversePrint(ListNode head) {
    	//存放遍历链表得到的数的数组
        int[] result=new int[10001];
        int i=10000;
        while(head!=null){
            result[i--]=head.val;
            head=head.next;
        }
		//要输出的数组
        int[] res=new int[10000-i];
        System.arraycopy(result, i+1, res, 0, 10000-i);
		
        return res;
    }
}

结果

在这里插入图片描述

总结

看了官方题解,是先用栈存放链表元素,因为栈具有先进后出的特点。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值