剑指 Offer 06. 从尾到头打印链表

剑指 Offer 06. 从尾到头打印链表

题目:https://leetcode.cn/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
在这里插入图片描述
解法一:Stack

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

}

解法二:ArrayList

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
   public int[] reversePrint(ListNode head) {
        ArrayList<ListNode> list=new ArrayList<>();
        while(head!=null){
            list.add(head);
            head=head.next;
        }
        int len= list.size();
        int[] nums=new int[len];
        for (int i = 0; i < len; i++) {
            nums[i]=list.get(len-i-1).val;
        }
        return nums;
    }

}

解法三:无需Stack和ArrayList

public int[] reversePrint(ListNode head) {
        //先获取链表长度,创建对应长度数组
        ListNode currNode = head;
        int len = 0;
        while(currNode != null){
            len ++;
            currNode = currNode.next;
        }
        int[] result = new int[len];
        
        //再次遍历链表,将值倒序填充至结果数组
        currNode = head;
        while(currNode != null){
            result[len - 1] = currNode.val;
            len --;
            currNode = currNode.next;
        }
        return result;
    }

解法三是先通过链表获取数组大小,从而逆序遍历数组赋值并返回。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值