美文网首页数据结构与算法
剑指 Offer 06 从尾到头打印链表

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

作者: itbird01 | 来源:发表于2021-12-06 07:14 被阅读0次

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

    题意:输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

    解题思路

    解法1:用Stack或者LinkedList数据结构,分别利用Stack(先入后出)、LinkedList(addFirst加入list头)的特性,然后遍历Stack或者LinkedList,构建结果数组
    解法2:如果题目要求过程中不可以使用其他数据结构,只可以在原链表上操作,得到结果数组。可以通过两次遍历法,第一次遍历得到链表的大小,然后就可以声明固定大小的数组,第二次遍历,将遍历到的数据,倒序插入数组即可


    执行效率

    解题遇到的问题

    后续需要总结学习的知识点

    ##解法1
    import java.util.LinkedList;
    
    class Solution {
        public int[] reversePrint(ListNode head) {
            LinkedList<Integer> linkedList = new LinkedList<Integer>();
            while (head != null) {
                linkedList.addFirst(head.val);
                head = head.next;
            }
            int[] ans = new int[linkedList.size()];
            for (int i = 0; i < linkedList.size(); i++) {
                ans[i] = linkedList.get(i);
            }
            return ans;
        }
    
        public class ListNode {
            int val;
            ListNode next;
            ListNode(int x) {
                val = x;
            }
        }
    }
    
    ##解法2
    class Solution {
        public int[] reversePrint(ListNode head) {
            int len = 0;
            ListNode tempListNode = head;
            while (tempListNode != null) {
                len++;
                tempListNode = tempListNode.next;
            }
            int[] ans = new int[len];
            for (int i = len - 1; i >= 0; i--) {
                ans[i] = head.val;
                head = head.next;
            }
            return ans;
        }
    
        public class ListNode {
            int val;
            ListNode next;
            ListNode(int x) {
                val = x;
            }
        }
    }
    

    相关文章

      网友评论

        本文标题:剑指 Offer 06 从尾到头打印链表

        本文链接:https://www.haomeiwen.com/subject/rcmvxrtx.html