首页 > 其他 > 详细

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

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

题目描述

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!