剑指Offer——从尾到头打印链表

1、题目描述

  输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

2、代码实现

 1 package com.baozi.offer;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Stack;
 5 
 6 /**
 7  * @author BaoZi
 8  * @create 2019-07-10-18:13
 9  */
10 public class Offer3 {
11     public static void main(String[] args) {
12         Offer3 offer3 = new Offer3();
13         ListNode l1 = new ListNode(1);
14         ListNode l2 = new ListNode(2);
15         ListNode l3 = new ListNode(3);
16         ListNode l4 = new ListNode(4);
17         l1.next = l2;
18         l2.next = l3;
19         l3.next = l4;
20         l4.next = null;
21         ArrayList<Integer> reslut = offer3.printListFromTailToHead(l1);
22         System.out.println(reslut.toString());
23     }
24 
25     public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
26         //1、创建一个目标变量,保存元素顺序和原链表的元素顺序刚好相反
27         ArrayList<Integer> list = new ArrayList<>();
28         //2、先判断给定的原链表是否为空,如果为空则直接返回一个空的目标链表
29         if (listNode == null) {
30             return list;
31         }
32         //3、根据题目要求,我们要把链表顺序从尾到头打印输出,所以设置一个栈的数据结构
33         Stack<Integer> stack = new Stack<>();
34         ListNode temp = listNode;
35         //4、通过while循环的方式先把原链表中的元素全部存入栈中
36         while (temp != null) {
37             stack.push(temp.val);
38             temp = temp.next;
39         }
40         //5、在通过while循环的方式把栈的元素逐一存入目标链表中
41         while (!stack.isEmpty()) {
42             list.add(stack.pop());
43         }
44         //6、此时的list链表的元素顺序和原链表的顺序就刚好相反了
45         return list;
46     }
47 }
48 
49 class ListNode {
50     int val;
51     ListNode next = null;
52 
53     ListNode(int val) {
54         this.val = val;
55     }
56 }
原文地址:https://www.cnblogs.com/BaoZiY/p/11165738.html