从头到尾打印链表

这篇博客介绍了如何从尾到头地遍历一个链表,并将其元素存储到一个ArrayList中。提供了两种解决方案:一是先反转链表再赋值,二是使用递归从后往前赋值。
摘要由CSDN通过智能技术生成

题目描述

输入一个链表,按链表从尾到头的顺序返回一个ArrayList。

解题思路

1、先将链表反转,然后再将里面的值赋给ArrayList;
2、使用递归,将链表里的值从后到前赋给ArrayList。

代码

代码一:

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
       ArrayList<Integer> list = new ArrayList<>();
        if(listNode == null){
            return list;
        }
        ListNode pre = listNode;
        ListNode cur = listNode;
        ListNode next = listNode.next;
        while(next != null){
            cur.next = next.next;
            next.next = pre;
            pre = next;
            next = cur.next;
        }
        while(pre != null){
            list.add(pre.val);
            pre = pre.next;
        }
        return list;
    }
}

代码二:

链接:https://www.nowcoder.com/questionTerminal/d0267f7f55b3412ba93bd35cfa8e8035?f=discussion
来源:牛客网

public class Solution {
    ArrayList<Integer> arrayList=new ArrayList<Integer>();
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        if(listNode!=null){
            this.printListFromTailToHead(listNode.next);
            arrayList.add(listNode.val);
        }
        return arrayList;
    }
}  
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值