zoukankan      html  css  js  c++  java
  • 剑指 Offer 06. 从尾到头打印链表

    题解

    迭代

    先求出链表的长度,最后反着添加元素即可

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public int[] reversePrint(ListNode head) {
            ListNode node = head;
            int count = 0;
            while(node != null){
                node = node.next;
                count ++;
            }
            int[] res = new int[count];
            for(int i = count - 1; i >= 0; -- i){
                res[i] = head.val;
                head = head.next;
            }
    
            return res;
        }
    }
    

    回溯

    直接利用回溯算法直接就是从后面添加

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        List<Integer> list = new ArrayList<>();
        public int[] reversePrint(ListNode head) {
            backTracking(head);
            int[] res = new int[list.size()];
            for(int i = 0; i < list.size(); ++ i){
                res[i] = list.get(i);
            }
            return res;
        }
    
        void backTracking(ListNode head){
            if(head == null) return;
            backTracking(head.next);
            list.add(head.val);
        }
    }
    
    如有错误,欢迎指正!
  • 相关阅读:
    证书格式转换
    emq知识点
    emq共享订阅
    SpringBoot
    Android网络编程Socket长连接
    Android 网络通信框架Volley简介(Google IO 2013)
    Android中的5种数据存储方式
    Android
    android解析XML总结(SAX、Pull、Dom三种方式)
    乔迁新禧
  • 原文地址:https://www.cnblogs.com/Lngstart/p/14624662.html
Copyright © 2011-2022 走看看