题目:输入一个链表的头结点,从尾到头反过来打印每个结点的值。
——来源于《剑指offer》
有两种思路,一种是借助数据结构——栈,先进后出的特点,另一种是递归代码实现 package com.qianyu.jianzhioffer; import java.util.*; /** * @author lijing * @date 2019-07-18-11:38 * @discroption 从尾到头打印链表 */ public class PrintListReversingly { /** * 表示结点的内部类 */ private static class Node { public Node next; public Object data; public Node(Node next, Object data) { this.next = next; this.data = data; } } public static void solution(Node head) { Node p = head; Stack stack = new Stack(); while (p != null) { stack.push(p.data); p = p.next; } while (!stack.isEmpty()) { System.out.print(stack.pop()); } } public static void solution2(Node head) { if (head == null) { return; } solution2(head.next); System.out.print(head.data); } public static void main(String[] args) { Node node5 = new Node(null, 5); Node node4 = new Node(node5, 4); Node node3 = new Node(node4, 3); Node node2 = new Node(node3, 2); Node head = new Node(node2, 1); solution(head); System.out.println(); solution2(head); } }