从尾到头打印链表(牛客网)

本文介绍三种方法实现链表从尾到头的逆序输出:递归法、栈结构法和三指针反转法。递归法利用递归特性反向遍历;栈结构法使用栈的后进先出原则;三指针法通过反转链表实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、题目描述:
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
二、解题思路:
这道题类似于反向输出链表的题目。有两种思路:
①递归解决,可以反向输出。(根据递归的特点)
②充分利用数据结构:栈的“后进先出”实现
③利用三个指针来反向输出链表(pre,current,next)
在这里插入图片描述

三、代码
①递归版本

/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/
import java.util.ArrayList;
public class Solution {
   ArrayList<Integer> arrayList = new ArrayList<Integer>();

   public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        if (listNode != null) {
            if (listNode.next != null) {
                printListFromTailToHead(listNode.next);
            }
            arrayList.add(listNode.val);
        }
        return arrayList;
    }
}

②栈结构版本

/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/

import java.util.ArrayList;
import java.util.Stack;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        Stack<Integer> stack=new Stack<Integer>();
        while(listNode!=null){
            stack.push(listNode.val);
            listNode=listNode.next;     
        }
                             
        ArrayList<Integer> list=new ArrayList<Integer>();
        while(!stack.isEmpty()){
            list.add(stack.pop());
        }
        return list;
    }
}

③三个指针

/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/

import java.util.ArrayList;
public class Solution {
   public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ListNode pre = null;
        ListNode current = listNode;
        ListNode reverseHead = null;
        //下面这部分是把整个链表反转
        if (current != null) {
            while (current != null) {
                ListNode next = current.next;
                if (next == null) {
                    reverseHead = current;
                }
                current.next=pre;
                pre = current;
                current = next;
            }
            current = reverseHead;
        }
        ArrayList<Integer> arrayList = new ArrayList<Integer>();
        while (current!= null) {
            arrayList.add(current.val);
            current = current.next;
        }
        return arrayList;
    }
}

题外话:牛客网的编辑器真的佩服了。。。(反正是需要细致的注意啦~~)
比如函数名从本地编辑器粘贴过来的时候是不是错了。。。
在这里插入图片描述这样子就可以(上面)

在这里插入图片描述
而中间一行加有空格就不可以!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值