剑指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     }

 

posted @ 2019-04-09 11:45  月半榨菜  阅读(91)  评论(0编辑  收藏  举报