码迷,mamicode.com
首页 > 其他好文 > 详细

剑指offer-从尾到头打印链表

时间:2019-04-09 12:31:08      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:递归   span   ack   item   方法   nod   offer   new   库函数   

题目描述

输入一个链表,按链表值从尾到头的顺序返回一个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     }

 

剑指offer-从尾到头打印链表

标签:递归   span   ack   item   方法   nod   offer   new   库函数   

原文地址:https://www.cnblogs.com/zhacai/p/10675997.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!