【剑指Offer】面试题6:从尾到头打印链表

本文介绍了一种在Java中实现链表从尾到头逆序输出的方法,包括使用ArrayList通过在0位置添加元素来实现反转输出、利用栈的后进先出特性以及采用递归方法。这些方法适用于不同的场景需求。

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

import java.util.ArrayList;
import java.util.Stack;

/**
 * 面试题6:从尾到头打印链表
 * 题目:输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
 *
 * @author dengjie
 * @create 2021-03-10 12:44
 */
public class Solution6 {
    static ArrayList<Integer> arrayList = new ArrayList<>();//方法三递归时使用
    public static void main(String[] args) {
        ListNode node = new ListNode(67);
        ListNode node1 = new ListNode(0);
        ListNode node2 = new ListNode(24);
        ListNode node3 = new ListNode(58);
        node.next = node1;
        node1.next = node2;
        node2.next = node3;
        System.out.println(node);

        ArrayList<Integer> res = printListFromTailToHeadByRecursive(node);
        System.out.println(res);


    }

    /**
     * 方法1:list.add(index,ele),在0位置处添加元素实现反转输出
     * @param listNode
     * @return
     */
    public static ArrayList<Integer> printListFromTailToHead(ListNode listNode){
        ArrayList<Integer> arr = new ArrayList<>();
        while (listNode != null){
            arr.add(0,listNode.val);
            listNode = listNode.next;
        }
        return arr;
    }
    /**
     * 方法二:栈
     */
    public static ArrayList<Integer> printListFromTailToHeadByStack(ListNode listNode){
        Stack<Integer> stack = new Stack<>();
        ArrayList<Integer> arrayList = new ArrayList<>();
        while (listNode != null){
            stack.push(listNode.val);
            listNode = listNode.next;
        }
        while (!stack.empty()){
            arrayList.add(stack.pop());
        }
        return arrayList;
    }

    /**
     * 方法三:递归
     */
    public static ArrayList<Integer> printListFromTailToHeadByRecursive(ListNode listNode){

        //注意是if不是while
        if (listNode != null){
            printListFromTailToHeadByRecursive(listNode.next);
            arrayList.add(listNode.val);
        }
        return arrayList;
    }
}

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

    @Override
    public String toString() {
        return "ListNode{" +
                "val=" + val +
                ", next=" + next +
                '}';
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值