🌀 技术人生
凡事有交代,件件有着落,事事有回音
从尾到头打印链表

题目描述:

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

思路:

方法一:

可以采用栈的先进后出实现

代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.util.ArrayList;
import java.util.Stack;
public class test031 {
    public static class ListNode {
        int val;
        //结点的值 
        ListNode next = null;
       //下一个结点 
    }

    public static class Solution {
        //* 使用栈的方式 /*/ 
        public ArrayList<Integer> test(ListNode listNode) {
            Stack<Integer> stack = new Stack<>();
            while (listNode != null) {
                stack.push(listNode.val);
                //进栈 
                listNode = listNode.next;
            }
            ArrayList<Integer> list = new ArrayList<>();
            while (!stack.isEmpty()) {
                list.add(stack.pop());
            }
            return list;
        }
    }

    public static void main(String[] args) {
        ListNode node = new ListNode();
        node.val = 1;
        node.next = new ListNode();
        node.next.val = 2;
        node.next.next = new ListNode();
        node.next.next.val = 3;
        node.next.next.next = new ListNode();
        node.next.next.next.val = 4;
        Solution solution = new Solution();
        ArrayList<Integer> list = solution.test(node);
        for (int i = 0; i < list.size(); i++) {
            System.out.print(list.get(i) + " ");
        }
    }
}

方法二:

使用递归实现

代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.util.ArrayList;
public class test032 {
    public static class ListNode {
        int val;
        //结点的值 
        ListNode next = null;
        //下一个结点 
    }

    public static class Solution {
        ArrayList<Integer> list = new ArrayList<Integer>();
        public ArrayList<Integer> test(ListNode listNode) {
            if (listNode != null) {
                this.test(listNode.next);
                list.add(listNode.val);
            }
            return list;
        }
    }

    public static void main(String[] args) {
        ListNode node = new ListNode();
        node.val = 1;
        node.next = new ListNode();
        node.next.val = 2;
        node.next.next = new ListNode();
        node.next.next.val = 3;
        node.next.next.next = new ListNode();
        node.next.next.next.val = 4;
        Solution solution = new Solution();
        ArrayList<Integer> list = solution.test(node);
        for (int i = 0; i < list.size(); i++) {
            System.out.print(list.get(i) + " ");
        }
    }
}

最后修改于 2021-03-13

知识共享许可协议
本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。