Java实现:输入一个链表,按链表从尾到头的顺序返回一个ArrayList。

解题思路:从头结点开始,遍历单向链表,定义一个 ArrayList<Integer> 集合对象保存链表中每个结点的值,注意在每次插入时,都将链表结点的值插入到 列表ArrayList的最前面(即索引值为0);

 1 import java.util.ArrayList;
 2 import java.util.Iterator;
 3 import java.util.Scanner;
 4 
 5 class ListNode {
 6     int val;
 7     ListNode next = null;
 8 
 9     ListNode(int val) {
10         this.val = val;
11     }
12 }
13 
14 public class Solution {
15     public static void main(String[] args) {
16         Scanner scanner = new Scanner(System.in);
17         String[] str = scanner.nextLine().split(" ");
18         ListNode listNode = null;
19         ListNode p = null;
20         ArrayList<Integer> result = new ArrayList<>();
21         if(str.length == 0) {
22             listNode = null;
23         }
24         else {
25             for (int i = 0; i < str.length; i++) {
26                 ListNode temp = new ListNode(Integer.parseInt(str[i]));
27                 if (listNode == null) {
28                     listNode = temp;
29                     p = temp;
30                 } else {
31                     p.next = temp;
32                     p = p.next;
33                 }
34             }
35         }
36         result = printListFromTailToHead(listNode);
37         Iterator<Integer> it = result.iterator();
38         while (it.hasNext()) {
39             System.out.print(it.next() + " ");
40         }
41         System.out.println();
42     }
43 
44     public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
45         ArrayList<Integer> result = new ArrayList<>();
46         if(listNode == null) {
47             return result;
48         }
49         else {
50             while (listNode != null) {
51                 // 每次都插入到第一个位置
52                 result.add(0, listNode.val);
53                 listNode = listNode.next;
54             }
55             return result;
56         }
57     }
58 }

猜你喜欢

转载自www.cnblogs.com/maxge/p/12807013.html
今日推荐