zoukankan      html  css  js  c++  java
  • 剑指offer-从尾到头打印链表

    题目描述

    输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
     
    方法一:利用ArrayList库函数
    1 public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {//链表 my
    2         ArrayList<Integer> re = new ArrayList<Integer>();
    3         while(null!=listNode){
    4             re.add(0,listNode.val);
    5             listNode = listNode.next;
    6         }
    7         return re;
    8     }

    方法二:使用递归

    1 public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {//链表 递归 mytip
    2         if(null==listNode){
    3             return new ArrayList<Integer>();
    4         }
    5         ArrayList<Integer> re = printListFromTailToHead(listNode.next);
    6         re.add(listNode.val);
    7         return re;
    8     }

    方法三:使用栈

     1 public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {//链表 栈 mytip
     2         Stack<Integer> stack = new Stack<Integer>();
     3         while(null!=listNode){
     4             stack.push(listNode.val);
     5             listNode = listNode.next;
     6         }
     7         ArrayList<Integer> re = new ArrayList<Integer>(stack.size());
     8         while(!stack.isEmpty()){
     9             re.add(stack.pop());
    10         }
    11         return re;
    12     }
  • 相关阅读:
    迭代器,生成器的理解
    需求
    关于dom 0级 2级 3级事件的理解
    夯实前端基础
    前端面试题 收集
    前端易忘点,持续更新
    form target 文件上传
    ES6 symbol
    bzoj1260 [CQOI2007]涂色paint
    bzoj1083 [SCOI2005]繁忙的都市
  • 原文地址:https://www.cnblogs.com/zhacai/p/10675997.html
Copyright © 2011-2022 走看看