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);
        }
    }
    
    如有错误,欢迎指正!
  • 相关阅读:
    为什么下水井盖是圆的
    静心尽力
    菜鸟的一年
    [转]Libev教程
    流媒体:V4L2视频获取
    [转]Libev源码分析 -- 整体设计
    c#操作xml增删改查
    dwz简单配置与操作
    jsonp 跨域访问
    操作cookie.判断浏览器系统版本,判断safir浏览器存储数据
  • 原文地址:https://www.cnblogs.com/Lngstart/p/14624662.html
Copyright © 2011-2022 走看看