1. import java.util.ArrayList;
    2. import java.util.LinkedList;
    3. import java.util.List;
    4. import java.util.Stack;
    5. /**
    6. * 面试题6:从尾到头打印链表
    7. * 输入一个链表的头节点,从尾到头反过来打印出每个节点的值
    8. */
    9. public class No6 {
    10. public static void main(String[] args) {
    11. //测试用例
    12. //1、输入的链表有多个(1个)节点
    13. //2、特殊输入测试
    14. ListNode test = new ListNode();
    15. test.add(4);
    16. test.add(5);
    17. test.add(6);
    18. test.print();
    19. System.out.println(methord2(test));
    20. }
    21. //栈实现。鲁棒性优于递归调用
    22. public static ArrayList<Integer> methord1(ListNode listNode){
    23. ArrayList<Integer> array = new ArrayList<>();
    24. Stack<ListNode> stack = new Stack<>();
    25. while(listNode != null){
    26. stack.push(listNode);
    27. listNode = listNode.next;
    28. }
    29. while(!stack.empty()){
    30. array.add(stack.pop().val);
    31. }
    32. return array;
    33. }
    34. //递归实现.注意,如果链表很长时,会导致函数调用层级很深,有可能导致函数调用栈溢出。
    35. public static ArrayList<Integer> methord2(ListNode listNode){
    36. ArrayList<Integer> array = new ArrayList<>();
    37. if(listNode!=null){
    38. if(listNode.next!=null){
    39. array = methord2(listNode.next);
    40. }
    41. array.add(listNode.val);
    42. }
    43. return array;
    44. }
    45. static class ListNode {
    46. int val; //数值 data
    47. ListNode next; // 结点 node
    48. ListNode(int x) { //可以定义一个有参构造方法,也可以定义一个无参构造方法
    49. val = x;
    50. }
    51. public ListNode() {
    52. }
    53. // 添加新的结点
    54. public void add(int newVal) {
    55. ListNode newNode = new ListNode(newVal);
    56. if (this.next == null)
    57. this.next = newNode;
    58. else
    59. this.next.add(newVal);
    60. }
    61. // 打印链表
    62. public void print() {
    63. System.out.print(this.val);
    64. if (this.next != null) {
    65. System.out.print("-->");
    66. this.next.print();
    67. }
    68. }
    69. }
    70. }