Fork me on GitHub

从尾到头打印链表

题目描述

输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
 1 import java.util.*;
 2 import java.util.Scanner;
 3 
 4 public class Main03 {
 5     public static void main(String[] args) {
 6         Scanner sc = new Scanner(System.in);
 7         ArrayList<Integer> array = new ArrayList<Integer>();
 8         
 9     }
10     
11     
12     public class ListNode {
13        int val;
14        ListNode next = null;
15        ListNode(int val) {
16            this.val = val;
17        }
18     }
19     
20 
21     public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
22         Stack<Integer> stack = new Stack<>();
23         while(listNode != null) {
24             stack.push(listNode.val);
25             listNode = listNode.next;
26         }
27         
28         ArrayList<Integer> array = new ArrayList();
29         if (!stack.isEmpty()) {
30             array.add(stack.pop());
31         }
32         return array;
33     }

 

posted @ 2019-06-10 20:30  gentleKay  阅读(100)  评论(0编辑  收藏  举报