zoukankan      html  css  js  c++  java
  • 剑指offer中经典的算法题之从头到尾打印链表

    话不多说上代码:

      我自己的算法是:

      

    /**
    *    public class ListNode {
    *        int val;
    *        ListNode next = null;
    *
    *        ListNode(int val) {
    *            this.val = val;
    *        }
    *    }
    *
    */
    import java.util.ArrayList;
    public class Solution {
        public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
            ArrayList<Integer> returnList = new ArrayList<Integer>();
            if(listNode == null){
                return returnList;
            }        
            ListNode re = reverse(listNode);
            while(re != null){
                returnList.add(re.val);
                re = re.next;
            }
            return returnList;
        }
        
        public static ListNode reverse(ListNode listNode){
            if(listNode.next == null){
                return listNode;
            }
            ListNode next = listNode.next;
            listNode.next = null;
            ListNode re = reverse(next);
            next.next = listNode;
            return re;
        }
    }

    这是我没有参考其他人的答案自己想出来的简单的算法,算是比较糟糕了,思路是先反转链表,再进行打印

    下面列出其他人比较经典的算法:

    1. 利用栈,先进后出

    2 . 递归

  • 相关阅读:
    协成
    进程与线程-多线程
    进程与线程2
    进程与线程
    socket编程
    常用模块二(hashlib、configparser、logging)
    异常处理
    python之路——面向对象进阶
    封装
    初识——面向对象
  • 原文地址:https://www.cnblogs.com/lwmp/p/9692094.html
Copyright © 2011-2022 走看看