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

这篇博客介绍了三种不同的方法来实现从尾到头打印链表节点值:1) 计算链表长度并反向填充数组;2) 使用堆栈保存指针;3) 递归实现。每种方法都通过实例代码详细阐述了其工作原理。

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
在这里插入图片描述

  1. 方法1
    计算链表的长度,反向填充数组
/**
 1. Definition for singly-linked list.
 2. public class ListNode {
 3.     int val;
 4.     ListNode next;
 5.     ListNode(int x) { val = x; }
 6. }
 */
class Solution {
    public int[] reversePrint(ListNode head) {
        ListNode n=head;
        int num=0;
        while(n!=null){
            num++;
            n=n.next;
        }
        int[] a=new int[num];
        n=head;
        for(int i=num-1;i>-1;i--){
            a[i]=n.val;
            n=n.next;
        }
        return a;
    }
}

2、堆栈
保存指针

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

保存数字

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

3、递归
递归和堆栈方法基本都能互换着写

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    List<Integer> t=new ArrayList<>();
    // ArrayList<Integer> t=new ArrayList<Integer>();
    public int[] reversePrint(ListNode head) {
        dg(head);
        int size=t.size();
        int[] a=new int[size];
        for(int i=0;i<size;i++){
            a[i]=t.get(i);
        }
        return a;
    }
    void xunhuan(ListNode head){
        if (head==null) return;
        dg(head.next);
        t.add(head.val);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值