栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

剑指Offer 17. 从尾到头打印链表-java实现

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

剑指Offer 17. 从尾到头打印链表-java实现

原题链接

输入一个链表的头结点,按照 从尾到头 的顺序返回节点的值。

返回的结果用数组存储。

数据范围
0≤ 链表长度 ≤1000。

样例
输入:[2, 3, 5]
返回:[5, 3, 2]

题解

本文介绍三种算法思路

第一种:1 先遍历一遍求长度 2 然后在遍历赋值 由于是数组 所以可以先赋值后面的
第二种:通过辅助栈的做法 1 先遍历一遍求得长度 2 然后通过stack.pop()赋值给数组
第三种: 使用递归方法,利用递归,先递推至链表末端;回溯时,依次将节点值加入列表,即可实现链表值的倒序输出。

第一种
 
class Solution {
    public int[] printListReversingly(ListNode head) {
        //先获得链表的长度 
        //在遍历赋值
        ListNode temp = head ;
        int len = 0 ;
        while(temp != null){
            ++len; 
            temp = temp.next;
        }
        int [] res = new int[len];
        int index = len -1 ;
        temp = head ;
        while (temp != null){
            res[index--] = temp.val ;
            temp= temp.next ;
        }
        return res ;
    }
}
第二种
 
class Solution {
    public int[] printListReversingly(ListNode head) {
       LinkedList stack = new LinkedList();
        while(head != null) {
            stack.push(head.val);
            head = head.next;
        }
        int[] res = new int[stack.size()];
        for(int i = 0; i < res.length; i++)
            res[i] = stack.pop();
    return res;

 
    }
}
第三种
 class Solution {
    ArrayList tmp = new ArrayList();
    public int[] reversePrint(ListNode head) {
        recur(head);
        int[] res = new int[tmp.size()];
        for(int i = 0; i < res.length; i++)
            res[i] = tmp.get(i);
        return res;
    }
    void recur(ListNode head) {
        if(head == null) return;
        recur(head.next);
        tmp.add(head.val);
    }
}

 
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/857158.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号