剑指offer-leetcode 第四题

链接:剑指offer-leetcode版


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

输入:head = [1,3,2]
输出:[2,3,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) {
        Stack<Integer> stack = new Stack<Integer>();
        ListNode temp = head;
        while(true){
            if(temp == null){
                break;
            }
            stack.push(temp.val);
            temp = temp.next;
        }
        int[] arr = new int[stack.size()];
        for(int i = 0;i<arr.length;i++){
            arr[i] = (Integer)stack.pop();
        }
        return arr;
    }
}

1、用栈的先进后出的特性来把链表中顺序便利的到的数字push进去

2、再通过stack.size()得到栈的长度来构建返回数组

3、通过一个for循环遍历把数组存到数组中,最后返回

另一种方法(时间击败百分之百用户,不压栈的方法)

/**
 * 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 temp = head;
        int size=0;
        //通过这个while循环可以得到链表的长度,通过这个长度可以区实例化一个数组
        while(temp !=null){//一直指向最后一个节点
            size++;
            temp = temp.next;
        }
        //实例化数组
        int[] res = new int[size];
        temp = head;
        //从后往前的往数组里面放值
        for(int i = size-1;i>=0;i--){
            res[i] = temp.val;
            temp = temp.next;
        }
        return res;
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值