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

[剑指offer刷题06] - 从尾到头打印链表

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

[剑指offer刷题06] - 从尾到头打印链表

题目[题目及部分解法来自LeeCode]
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
solution one: 先找出链表长度,之后依次向数组末尾添加元素【这也是数组逆置的一种方法!】
    public static int[] reversePrint1(ListNode head) {
        if(head == null)
        {
            int[] arr = new int[0];
            return arr;
        }
        ListNode temp = head;
        int len = 0;
        while(temp.next != null)
        {
            temp = temp.next;
            ++len;
        }
        temp = head;
        System.out.println(len);
        int[] arr = new int[len];
        while(temp.next != null)
        {
            arr[len - 1] = temp.val;
            temp = temp.next;
            --len;
        }
        return arr;
    }
solution two: 先将链表倒置,之后依次添加到数组中。
    public static int[] reversePrint3(ListNode head){
        if(head == null)
        {
            int[] arr = new int[0];
            return arr;
        }
        ListNode temp = head;
        ListNode temp1 = head.next;
        ListNode temp2;
        temp.next = null;
        int counter = 1;
        int arrIndex = 0;
        while(temp1.next != null){
            temp2 = temp1.next;
            temp1.next = temp;
            temp = temp1;
            temp1 = temp2;
            ++counter;
        }
        int[] arr = new int[counter];
        while(temp != null)
        {
            arr[arrIndex] = temp.val;
            ++arrIndex;
            temp = temp.next;
        }
        return arr;
    }
solution three: 利用栈先进后出的特性,将链表元素先依次全部压入栈中,再依次取出添加进数组中。
    public static int[] reversePrint4(ListNode head){
        Stack stack = new Stack();
        ListNode temp = head;
        while(temp.next != null)
        {
            stack.push(temp);
            temp = temp.next;
        }
        int size = stack.size();
        int[] arr = new int[size];
        for(int i = 0; i < size; ++i){
            arr[i] = stack.pop().val;
        }
        return arr;
    }

next part , 来复习下java Stack类


Java Stack类

栈是Vector的一个子类,它实现了一个标准的后进先出的栈。堆栈只定义了默认构造函数,用来创建一个空栈。 堆栈除了包括由Vector定义的所有方法,也定义了自己的一些方法。boolean empty() :测试堆栈是否为空。Object peek( ):查看堆栈顶部的对象,但不从堆栈中移除它。Object pop( ):移除堆栈顶部的对象,并作为此函数的值返回该对象。Object push(Object element):把项压入堆栈顶部。int search(Object element):返回对象在堆栈中的位置,以 1 为基数。

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

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

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